Java Code Examples for org.geotools.map.MapContent#addLayer()

The following examples show how to use org.geotools.map.MapContent#addLayer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MapRender.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Render vector symbol.
 *
 * @param mapContent the map content
 * @param styledLayer the styled layer
 * @param style the style
 */
private void renderVectorSymbol(MapContent mapContent, StyledLayer styledLayer, Style style) {
    FeatureSource<SimpleFeatureType, SimpleFeature> tmpFeatureList = null;

    if (styledLayer instanceof UserLayer) {
        if (userLayerFeatureListMap != null) {
            tmpFeatureList = userLayerFeatureListMap.get(styledLayer);
        }
    } else {
        tmpFeatureList = featureList;
    }

    if (tmpFeatureList != null) {
        mapContent.addLayer(
                new FeatureLayer(tmpFeatureList, (org.geotools.styling.Style) style));
        try {
            mapPane.setDisplayArea(tmpFeatureList.getBounds());
        } catch (IOException e) {
            ConsoleManager.getInstance().exception(this, e);
        }
    }
}
 
Example 2
Source File: GridCoverageNwwLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private static GTRenderer getRenderer( File rasterFile ) {

        AbstractGridFormat format = GridFormatFinder.findFormat(rasterFile);
        AbstractGridCoverage2DReader coverageReader = format.getReader(rasterFile);

        MapContent mapContent = new MapContent();
        try {

            Style rasterStyle = SldUtilities.getStyleFromFile(rasterFile);
            if (rasterStyle == null) {
                RasterSymbolizer sym = SldUtilities.sf.getDefaultRasterSymbolizer();
                rasterStyle = SLD.wrapSymbolizers(sym);
            }

            GridReaderLayer layer = new GridReaderLayer(coverageReader, rasterStyle);
            mapContent.addLayer(layer);
            mapContent.getViewport().setCoordinateReferenceSystem(CrsUtilities.WGS84);
        } catch (Exception e) {
            e.printStackTrace();
        }
        GTRenderer renderer = new StreamingRenderer();
        renderer.setMapContent(mapContent);
        return renderer;
    }
 
Example 3
Source File: MapRender.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Render raster symbol.
 *
 * @param mapContent the map content
 * @param style the style
 */
private void renderRasterSymbol(MapContent mapContent, Style style) {
    GridReaderLayer gridLayer =
            new GridReaderLayer(gridCoverage, (org.geotools.styling.Style) style);
    mapContent.addLayer(gridLayer);
    mapContent.getViewport().setBounds(gridLayer.getBounds());
    if (gridCoverage != null) {
        mapPane.setDisplayArea(gridCoverage.getOriginalEnvelope());
    }
}
 
Example 4
Source File: ShapeFileViewer.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {
	setSite(site);
	final FileEditorInput fi = (FileEditorInput) input;
	file = fi.getFile();
	final IPath path = fi.getPath();
	final File f = path.makeAbsolute().toFile();
	try {
		pathStr = f.getAbsolutePath();
		final ShapefileDataStore store = new ShapefileDataStore(f.toURI().toURL());
		store.setCharset(Charset.forName("UTF8"));
		content = new MapContent();
		featureSource = store.getFeatureSource();
		style = Utils.createStyle2(featureSource);
		layer = new FeatureLayer(featureSource, style);
		mode = determineMode(featureSource.getSchema(), "Polygon");
		final List<FeatureTypeStyle> ftsList = style.featureTypeStyles();
		if (ftsList.size() > 0) {
			fts = ftsList.get(0);
		} else {
			fts = null;
		}
		if (fts != null) {
			this.setFillColor(PreferencesHelper.SHAPEFILE_VIEWER_FILL.getValue(), mode, fts);
			this.setStrokeColor(PreferencesHelper.SHAPEFILE_VIEWER_LINE_COLOR.getValue(), mode, fts);
			((StyleLayer) layer).setStyle(style);
		}
		content.addLayer(layer);
	} catch (final IOException e) {
		DEBUG.ERR("Unable to view file " + path);
	}
	this.setPartName(path.lastSegment());
	setInput(input);
}
 
Example 5
Source File: RasterizedShapefilesFolderNwwLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private static GTRenderer getRenderer(File shapeFilesFolder) {
    File[] shpFiles = shapeFilesFolder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".shp");
        }
    });

    MapContent mapContent = new MapContent();
    for (File shpFile : shpFiles) {
        try {
            SimpleFeatureCollection readFC = NwwUtilities.readAndReproject(shpFile.getAbsolutePath());
            ReferencedEnvelope tmpBounds = readFC.getBounds();
            if (tmpBounds.getWidth() == 0 || tmpBounds.getHeight() == 0) {
                System.err.println("Ignoring: " + shpFile);
                continue;
            }
            // if (bounds == null) {
            // bounds = new ReferencedEnvelope(tmpBounds);
            // } else {
            // bounds.expandToInclude(tmpBounds);
            // }
            Style style = SldUtilities.getStyleFromFile(shpFile);
            if (style == null)
                style = SLD.createSimpleStyle(readFC.getSchema());

            FeatureLayer layer = new FeatureLayer(readFC, style);
            mapContent.addLayer(layer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mapContent);
    return renderer;
}
 
Example 6
Source File: RasterizedFeatureCollectionLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private static GTRenderer getRenderer( SimpleFeatureCollection featureCollectionLL, Style style ) {
    MapContent mapContent = new MapContent();
    try {
        FeatureLayer layer = new FeatureLayer(featureCollectionLL, style);
        mapContent.addLayer(layer);
    } catch (Exception e) {
        e.printStackTrace();
    }
    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mapContent);
    return renderer;
}
 
Example 7
Source File: RasterizedSpatialiteLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private static GTRenderer getRenderer( ASpatialDb db, String tableName, int featureLimit, Style style ) {
    MapContent mapContent = new MapContent();

    // read data and convert it to featurecollection
    try {
        long t1 = System.currentTimeMillis();
        System.out.println("STARTED READING: " + tableName);

        String databasePath = db.getDatabasePath();
        File dbFile = new File(databasePath);
        File parentFolder = dbFile.getParentFile();
        if (style == null) {
            File sldFile = new File(parentFolder, tableName + ".sld");
            if (sldFile.exists()) {
                style = SldUtilities.getStyleFromFile(sldFile);
            }
        }

        DefaultFeatureCollection fc = SpatialDbsImportUtils.tableToFeatureFCollection(db, tableName, featureLimit,
                NwwUtilities.GPS_CRS_SRID, null);
        long t2 = System.currentTimeMillis();
        System.out.println("FINISHED READING: " + tableName + " -> " + ((t2 - t1) / 1000) + "sec");
        if (style == null) {
            style = SLD.createSimpleStyle(fc.getSchema());
        }
        FeatureLayer layer = new FeatureLayer(fc, style);

        long t3 = System.currentTimeMillis();
        System.out.println("FINISHED BUILDING: " + tableName + " -> " + ((t3 - t2) / 1000) + "sec");

        mapContent.addLayer(layer);
    } catch (Exception e) {
        e.printStackTrace();
    }
    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mapContent);
    return renderer;
}
 
Example 8
Source File: OmsCoverageViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void viewCoverage() throws Exception {
    StyleFactory sf = CommonFactoryFinder.getStyleFactory(null);
    // RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
    // Style rasterStyle = SLD.wrapSymbolizers(sym);

    StyleBuilder sB = new StyleBuilder(sf);
    RasterSymbolizer rasterSym = sf.createRasterSymbolizer();

    ColorMap colorMap = sf.createColorMap();

    RenderedImage renderedImage = raster.getRenderedImage();
    double max = Double.NEGATIVE_INFINITY;
    double min = Double.POSITIVE_INFINITY;
    RectIter iter = RectIterFactory.create(renderedImage, null);
    do {
        do {
            double value = iter.getSampleDouble();
            if (value > max) {
                max = value;
            }
            if (value < min) {
                min = value;
            }
        } while( !iter.nextPixelDone() );
        iter.startPixels();
    } while( !iter.nextLineDone() );

    // red to blue
    Color fromColor = Color.blue;
    Color toColor = Color.red;
    Expression fromColorExpr = sB
            .colorExpression(new java.awt.Color(fromColor.getRed(), fromColor.getGreen(), fromColor.getBlue(), 255));
    Expression toColorExpr = sB
            .colorExpression(new java.awt.Color(toColor.getRed(), toColor.getGreen(), toColor.getBlue(), 255));
    Expression fromExpr = sB.literalExpression(min);
    Expression toExpr = sB.literalExpression(max);

    ColorMapEntry entry = sf.createColorMapEntry();
    entry.setQuantity(fromExpr);
    entry.setColor(fromColorExpr);
    colorMap.addColorMapEntry(entry);

    entry = sf.createColorMapEntry();
    entry.setQuantity(toExpr);
    entry.setColor(toColorExpr);
    colorMap.addColorMapEntry(entry);

    rasterSym.setColorMap(colorMap);

    Style rasterStyle = SLD.wrapSymbolizers(rasterSym);

    // Set up a MapContext with the two layers
    final MapContent map = new MapContent();
    map.setTitle("Coverage Viewer");
    map.addLayer(new GridCoverageLayer(raster, rasterStyle));

    // Create a JMapFrame with a menu to choose the display style for the
    final JMapFrame frame = new JMapFrame(map);
    frame.setSize(800, 600);
    frame.enableStatusBar(true);
    frame.enableTool(JMapFrame.Tool.ZOOM, JMapFrame.Tool.PAN, JMapFrame.Tool.RESET);
    frame.enableToolBar(true);
    frame.setVisible(true);
    frame.addWindowListener(new WindowAdapter(){
        public void windowClosing( WindowEvent e ) {
            frame.setVisible(false);
        }
    });

    while( frame.isVisible() ) {
        Thread.sleep(300);
    }
}
 
Example 9
Source File: OmsMapsViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void addImageMosaic( MapContent map ) throws Exception {
    if (inImageMosaics != null) {
        RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
        Style style = SLD.wrapSymbolizers(sym);

        final ParameterValue<Color> inTransp = AbstractGridFormat.INPUT_TRANSPARENT_COLOR.createValue();
        inTransp.setValue(Color.white);

        final ParameterValue<Color> outTransp = ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR.createValue();
        outTransp.setValue(Color.white);
        final ParameterValue<Color> backColor = ImageMosaicFormat.BACKGROUND_COLOR.createValue();
        backColor.setValue(Color.RED);
        final ParameterValue<Boolean> fading = ImageMosaicFormat.FADING.createValue();
        fading.setValue(true);

        final ParameterValue<Interpolation> interpol = ImageMosaicFormat.INTERPOLATION.createValue();
        interpol.setValue(new javax.media.jai.InterpolationBilinear());

        final ParameterValue<Boolean> resol = ImageMosaicFormat.ACCURATE_RESOLUTION.createValue();
        resol.setValue(true);

        
        final ParameterValue<Boolean> multiThread= ImageMosaicFormat.ALLOW_MULTITHREADING.createValue();
        multiThread.setValue(true);

        final ParameterValue<Boolean> usejai = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue();
        usejai.setValue(false);

        final ParameterValue<double[]> bkg = ImageMosaicFormat.BACKGROUND_VALUES.createValue();
        bkg.setValue(new double[]{0});

        GeneralParameterValue[] gp = new GeneralParameterValue[]{inTransp, multiThread};

        for( String imageMosaicPath : inImageMosaics ) {
            ImageMosaicReader imr = new ImageMosaicReader(new File(imageMosaicPath));
            GridReaderLayer layer = new GridReaderLayer(imr, style, gp);
            map.addLayer(layer);
        }
    }

}
 
Example 10
Source File: OmsMapsViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void addFeatureCollections( MapContent map ) throws Exception {
    if (inVectors == null) {
        return;
    }
    for( String path : inVectors ) {
        SimpleFeatureCollection fc = OmsVectorReader.readVector(path);
        GeometryDescriptor geometryDescriptor = fc.getSchema().getGeometryDescriptor();
        EGeometryType type = EGeometryType.forGeometryDescriptor(geometryDescriptor);

        File file = new File(path);
        Style style = SldUtilities.getStyleFromFile(file);

        switch( type ) {
        case MULTIPOLYGON:
        case POLYGON:
            if (style == null) {
                Stroke polygonStroke = sf.createStroke(ff.literal(Color.BLUE), ff.literal(2));
                Fill polygonFill = sf.createFill(ff.literal(Color.BLUE), ff.literal(0.0));

                Rule polygonRule = sf.createRule();
                PolygonSymbolizer polygonSymbolizer = sf.createPolygonSymbolizer(polygonStroke, polygonFill, null);
                polygonRule.symbolizers().add(polygonSymbolizer);

                FeatureTypeStyle polygonFeatureTypeStyle = sf.createFeatureTypeStyle();
                polygonFeatureTypeStyle.rules().add(polygonRule);

                style = sf.createStyle();
                style.featureTypeStyles().add(polygonFeatureTypeStyle);
                style.setName("polygons");
            }
            break;
        case MULTIPOINT:
        case POINT:
            if (style == null) {
                Mark circleMark = sf.getCircleMark();
                Fill fill = sf.createFill(ff.literal(Color.RED));
                circleMark.setFill(fill);
                // circleMark.setStroke(null);

                Graphic gr = sf.createDefaultGraphic();
                gr.graphicalSymbols().clear();
                gr.graphicalSymbols().add(circleMark);
                Expression size = ff.literal(6);
                gr.setSize(size);

                Rule pointRule = sf.createRule();
                PointSymbolizer pointSymbolizer = sf.createPointSymbolizer(gr, null);
                pointRule.symbolizers().add(pointSymbolizer);

                FeatureTypeStyle pointsFeatureTypeStyle = sf.createFeatureTypeStyle();
                pointsFeatureTypeStyle.rules().add(pointRule);

                style = sf.createStyle();
                style.featureTypeStyles().add(pointsFeatureTypeStyle);
                style.setName("points");
            }
            break;
        case MULTILINESTRING:
        case LINESTRING:
            if (style == null) {
                Stroke lineStroke = sf.createStroke(ff.literal(Color.RED), ff.literal(2));

                Rule lineRule = sf.createRule();
                LineSymbolizer lineSymbolizer = sf.createLineSymbolizer(lineStroke, null);
                lineRule.symbolizers().add(lineSymbolizer);

                FeatureTypeStyle lineFeatureTypeStyle = sf.createFeatureTypeStyle();
                lineFeatureTypeStyle.rules().add(lineRule);

                style = sf.createStyle();
                style.featureTypeStyles().add(lineFeatureTypeStyle);
                style.setName("lines");
            }
            break;

        default:
            break;
        }

        FeatureLayer layer = new FeatureLayer(fc, style);
        map.addLayer(layer);

    }

}
 
Example 11
Source File: OmsMapsViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void addCoverages( final MapContent map ) throws Exception {
    if (inRasters == null) {
        return;
    }
    RasterSymbolizer rasterSym = sf.createRasterSymbolizer();
    ColorMap colorMap = sf.createColorMap();

    for( String rasterPath : inRasters ) {
        GridCoverage2D readRaster = OmsRasterReader.readRaster(rasterPath);
        RenderedImage renderedImage = readRaster.getRenderedImage();
        double max = Double.NEGATIVE_INFINITY;
        double min = Double.POSITIVE_INFINITY;
        RectIter iter = RectIterFactory.create(renderedImage, null);
        do {
            do {
                double value = iter.getSampleDouble();
                if (value > max) {
                    max = value;
                }
                if (value < min) {
                    min = value;
                }
            } while( !iter.nextPixelDone() );
            iter.startPixels();
        } while( !iter.nextLineDone() );

        // red to blue
        Color fromColor = Color.blue;
        Color midColor = Color.green;
        Color toColor = Color.red;
        Expression fromColorExpr = sb
                .colorExpression(new java.awt.Color(fromColor.getRed(), fromColor.getGreen(), fromColor.getBlue(), 255));
        Expression midColorExpr = sb
                .colorExpression(new java.awt.Color(midColor.getRed(), midColor.getGreen(), midColor.getBlue(), 255));
        Expression toColorExpr = sb
                .colorExpression(new java.awt.Color(toColor.getRed(), toColor.getGreen(), toColor.getBlue(), 255));
        Expression fromExpr = sb.literalExpression(min);
        Expression midExpr = sb.literalExpression(min + (max - min) / 2);
        Expression toExpr = sb.literalExpression(max);

        ColorMapEntry entry = sf.createColorMapEntry();
        entry.setQuantity(fromExpr);
        entry.setColor(fromColorExpr);
        colorMap.addColorMapEntry(entry);

        entry = sf.createColorMapEntry();
        entry.setQuantity(midExpr);
        entry.setColor(midColorExpr);
        colorMap.addColorMapEntry(entry);

        entry = sf.createColorMapEntry();
        entry.setQuantity(toExpr);
        entry.setColor(toColorExpr);
        colorMap.addColorMapEntry(entry);

        rasterSym.setColorMap(colorMap);

        Style rasterStyle = SLD.wrapSymbolizers(rasterSym);

        GridCoverageLayer layer = new GridCoverageLayer(readRaster, rasterStyle);

        map.addLayer(layer);
    }
}
 
Example 12
Source File: MapUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
public static BufferedImage render( InternalMap map, Integer maxWidth, Integer maxHeight )
{
    MapContent mapContent = new MapContent();

    // Convert map objects to features, and add them to the map
    
    for ( InternalMapLayer mapLayer : map.getLayers() )
    {
        for ( InternalMapObject mapObject : mapLayer.getMapObjects() )
        {
            mapContent.addLayer( createFeatureLayerFromMapObject( mapObject ) );
        }
    }

    // Create a renderer for this map
    
    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent( mapContent );

    // Calculate image height
    
    ReferencedEnvelope mapBounds = mapContent.getMaxBounds();
    double widthToHeightFactor = mapBounds.getSpan( 0 ) / mapBounds.getSpan( 1 );
    int[] widthHeight = getWidthHeight( maxWidth, maxHeight, LegendSet.LEGEND_TOTAL_WIDTH, TITLE_HEIGHT, widthToHeightFactor );
    
    //LegendSet.LEGEND_TOTAL_WIDTH;
    
    Rectangle imageBounds = new Rectangle( 0, 0, widthHeight[0], widthHeight[1] );

    // Create an image and get the graphics context from it
    
    BufferedImage image = new BufferedImage( imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_ARGB );
    Graphics2D graphics = (Graphics2D) image.getGraphics();

    graphics.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
    
    renderer.paint( graphics, imageBounds, mapBounds );

    mapContent.dispose();
    
    return image;
}