/** * tell this layer where to plot itself * * @param map */ public void setMap(MapContent map) { clearMap(); // remember the map _myMap = map; // read ourselves in File openFile = new File(super.getFilename()); if (openFile != null && openFile.exists()) { _myLayer = loadLayer(openFile); } else { CorePlugin.logError(Status.WARNING, "GeoTools file not found:" + super.getFilename(), null); CorePlugin.showMessage( "Load GIS dataset", "Sorry, can't find the file:\n" + super.getFilename()); } // ok, add ourselves to the map if (_myLayer != null) { // sort out the visibility _myLayer.setVisible(this.getVisible()); _myLayer.setTitle(super.getName()); _myMap.addLayer(_myLayer); } }
/** * It sets the visibility of the layer. If the visibility changed, then the map will be refreshed. * * @param visible */ public void setVisible(boolean visible) { for (Layer mapLayer : this.mapLayers) { if (mapLayer.isVisible() != visible) { mapLayer.setVisible(visible); } } }
@Test public void testInterpolationByLayer() throws Exception { StreamingRenderer sr = new StreamingRenderer(); Layer layer = new FeatureLayer(createLineCollection(), createLineStyle()); // default is nearest neighbor assertEquals( sr.getRenderingInterpolation(layer), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); // test all possible values layer .getUserData() .put( StreamingRenderer.BYLAYER_INTERPOLATION, Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); assertEquals( sr.getRenderingInterpolation(layer), Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); layer .getUserData() .put( StreamingRenderer.BYLAYER_INTERPOLATION, Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); assertEquals( sr.getRenderingInterpolation(layer), Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); layer .getUserData() .put( StreamingRenderer.BYLAYER_INTERPOLATION, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); assertEquals( sr.getRenderingInterpolation(layer), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); }
@Test public void testDrawIntepolation() throws Exception { MapContent mc = new MapContent(); ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180, 180, -90, 90), DefaultGeographicCRS.WGS84); BufferedImage testImage = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR); GridCoverage2D testCoverage = new GridCoverageFactory().create("test", testImage, reWgs); GridCoverage2D coverage = new GridCoverage2D("test", testCoverage); // mocking a GridCoverageReader to wrap the testing coverage GridCoverage2DReader gridCoverageReader = Mockito.mock(GridCoverage2DReader.class); Mockito.when(gridCoverageReader.getOriginalEnvelope()).thenReturn(new GeneralEnvelope(reWgs)); Mockito.when(gridCoverageReader.getCoordinateReferenceSystem()) .thenReturn(DefaultGeographicCRS.WGS84); Mockito.when(gridCoverageReader.read(Mockito.any(GeneralParameterValue[].class))) .thenReturn(coverage); Layer layer = new FeatureLayer( FeatureUtilities.wrapGridCoverageReader( gridCoverageReader, new GeneralParameterValue[] {}), createRasterStyle()); layer .getUserData() .put( StreamingRenderer.BYLAYER_INTERPOLATION, Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); mc.addLayer(layer); BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR); StreamingRenderer sr = new StreamingRenderer(); sr.setMapContent(mc); Graphics2D graphics = (Graphics2D) image.getGraphics(); sr.paint(graphics, new Rectangle(200, 200), reWgs); // test right interpolation hint is set on Graphics2D assertEquals( graphics.getRenderingHint(JAI.KEY_INTERPOLATION), Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); layer .getUserData() .put( StreamingRenderer.BYLAYER_INTERPOLATION, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); sr.paint(graphics, new Rectangle(200, 200), reWgs); // test right interpolation hint is set on Graphics2D assertEquals( graphics.getRenderingHint(JAI.KEY_INTERPOLATION), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); }
ReferencedEnvelope bounds(Layer layer, WMSMapContent map) { ReferencedEnvelope e = layer.getBounds(); if (e == null) { e = bounds(map); } return e; }
@Override protected void finalize() throws Throwable { // ok, ditch the layer if (_myLayer != null) _myLayer.dispose(); // and let the parent do it's stuff super.finalize(); }
/** * Called when a new map layer has been added. Sets the layer as selected (for queries) and, if * the layer table is being used, adds the new layer to the table. */ public void layerAdded(MapLayerListEvent event) { Layer layer = event.getElement(); if (layerTable != null) { layerTable.onAddLayer(layer); } layer.setSelected(true); redrawBaseImage = true; boolean atFullExtent = equalsFullExtent(getDisplayArea()); boolean firstLayer = content.layers().size() == 1; if (firstLayer || atFullExtent) { reset(); if (firstLayer) { setCrs(layer.getBounds().getCoordinateReferenceSystem()); return; } } if (!isDisposed()) redraw(); }
/** * Returns true if the request is GWC compatible * * @param mapContent * @return */ public static boolean isRequestGWCCompatible(WMSMapContent mapContent, Layer layer, WMS wms) { List<Layer> layers = mapContent.layers(); for (int i = 0; i < layers.size(); i++) { if (layers.get(i) == layer) { return isRequestGWCCompatible(mapContent.getRequest(), i, wms); } } LOGGER.warning("Could not find map layer " + layer.getTitle() + " in the map context"); return false; }
/** forget about any existing map/layer */ public void clearMap() { if (_myLayer != null) { // remove ourselves from the map if (_myMap != null) { _myMap.removeLayer(_myLayer); } _myLayer.dispose(); _myLayer = null; } _myMap = null; }
/** * Set the map context for this map pane to display * * @param content the map context */ public void setMapContent(MapContent content) { if (this.content != content) { if (this.content != null) { this.content.removeMapLayerListListener(this); // for( MapLayer layer : this.context.getLayers() ) { // if (layer instanceof ComponentListener) { // removeComponentListener((ComponentListener) layer); // } // } } this.content = content; if (content != null) { this.content.addMapLayerListListener(this); this.content.addMapBoundsListener(this); // set all layers as selected by default for the info tool for (Layer layer : content.layers()) { layer.setSelected(true); // if (layer instanceof ComponentListener) { // addComponentListener((ComponentListener) layer); // } } setFullExtent(); } if (renderer != null) { renderer.setMapContent(this.content); } MapPaneEvent ev = new MapPaneEvent(this, MapPaneEvent.Type.NEW_CONTEXT); publishEvent(ev); } }
public static void legendAction() { try { LegendColorTable.countTable = 0; Layer layer = content.layers().get(content.layers().size() - 1); SimpleFeatureSource featureSource = (SimpleFeatureSource) layer.getFeatureSource(); String fieldName = getFieldForColour(featureSource); if (fieldName != null && fieldName.length() > 0) { Style style = createStyle(featureSource, fieldName); content.removeLayer(layer); Layer newLayer = new FeatureLayer(featureSource, style); content.addLayer(newLayer); } else throw new NullPointerException("Error occured during making legend"); } catch (ArrayIndexOutOfBoundsException ex) { JOptionPane.showMessageDialog(null, "No layers are added !"); } catch (Exception ex) { ex.printStackTrace(); // JOptionPane.showMessageDialog(null, ex.getMessage()); } }
private void addLayersListeners() { MapContent generalContext = ((MapTilesCache) cache).getMapDisplayContext(); MapContent lightweightContext = ((MapTilesCache) lightweightCache).getMapDisplayContext(); generalChangesReflector = new LayersChangesReflector(cache); lightChangesReflector = new LayersChangesReflector(lightweightCache); screenChangesReflector = new ScreenChangesReflector(); for (Layer layer : generalContext.layers()) { layer.addMapLayerListener(generalChangesReflector); } for (Layer layer : lightweightContext.layers()) { layer.addMapLayerListener(lightChangesReflector); } if (screenContext != null) { for (Layer layer : screenContext.layers()) { layer.addMapLayerListener(screenChangesReflector); } } }
private void removeLayersListeners() { MapContent generalContext = ((MapTilesCache) cache).getMapDisplayContext(); MapContent lightweightContext = ((MapTilesCache) lightweightCache).getMapDisplayContext(); if (generalChangesReflector != null) { for (Layer layer : generalContext.layers()) { layer.removeMapLayerListener(generalChangesReflector); } } if (lightChangesReflector != null) { for (Layer layer : lightweightContext.layers()) { layer.removeMapLayerListener(lightChangesReflector); } } if (screenContext != null && screenChangesReflector != null) { for (Layer layer : screenContext.layers()) { layer.removeMapLayerListener(screenChangesReflector); } } }
/** * It gets the visibility of the layer. * * @return */ public boolean isVisible() { for (Layer mapLayer : this.mapLayers) { return mapLayer.isVisible(); } return false; }
private List<ZGroupLayerPainter> buildLayerPainters( Graphics2D graphics, StreamingRenderer renderer, String layerId, ProgressListener cancellationListener) throws IOException, FactoryException, NoninvertibleTransformException, SchemaException, TransformException { List<ZGroupLayerPainter> painters = new ArrayList<>(); boolean closePainters = true; try { for (Layer layer : layers) { // get the LiteFeatureTypeStyle for this layer final FeatureSource featureSource = layer.getFeatureSource(); if (featureSource == null) { throw new IllegalArgumentException("The layer does not contain a feature source"); } final FeatureType schema = featureSource.getSchema(); final ArrayList<LiteFeatureTypeStyle> lfts = renderer.createLiteFeatureTypeStyles(layer, graphics, false); if (lfts.isEmpty()) { continue; } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Processing " + lfts.size() + " stylers for " + schema.getName()); } } // get the feature iterator we need FeatureCollection features = renderer.getFeatures(layer, schema, lfts); // While we could use a non mark feature iterator for single fts layers, // that would cause multiple connections to be open at the same time, // which in turn could cause deadlocks against connection pools, so we // are going to build a MarkFeatureIterator regardless // TODO: we could optimize down to simple streaming painting if we end up // with a single painter with a single fts (due to scale dependencies) // but we'd have to delay opening the MarkFeatureIterator to recognize the // situation int maxFeatures = SortedFeatureReader.getMaxFeaturesInMemory(layer.getQuery()); MarkFeatureIterator fi = MarkFeatureIterator.create(features, maxFeatures, cancellationListener); if (fi.hasNext()) { ZGroupLayerPainter painter = new ZGroupLayerPainter(fi, lfts, renderer, layerId); painters.add(painter); } else { fi.close(); } } // got to the end cleanly, no need to close the painters accumulated so far closePainters = false; } finally { if (closePainters) { for (ZGroupLayerPainter painter : painters) { try { painter.close(); } catch (Exception e) { LOGGER.log(Level.FINE, "Failed to close cleanly layer painter " + painter, e); } } } } validateSortBy(painters); return painters; }
/** * Loads the feature collection based on the current styling and the scale denominator. If no * feature is going to be returned a null feature collection will be returned instead * * @param featureSource * @param layer * @param mapContent * @param wms * @param scaleDenominator * @return * @throws Exception */ public static SimpleFeatureCollection loadFeatureCollection( SimpleFeatureSource featureSource, Layer layer, WMSMapContent mapContent, WMS wms, double scaleDenominator) throws Exception { SimpleFeatureType schema = featureSource.getSchema(); Envelope envelope = mapContent.getRenderingArea(); ReferencedEnvelope aoi = new ReferencedEnvelope(envelope, mapContent.getCoordinateReferenceSystem()); CoordinateReferenceSystem sourceCrs = schema.getCoordinateReferenceSystem(); boolean reprojectBBox = (sourceCrs != null) && !CRS.equalsIgnoreMetadata(aoi.getCoordinateReferenceSystem(), sourceCrs); if (reprojectBBox) { aoi = aoi.transform(sourceCrs, true); } Filter filter = createBBoxFilter(schema, aoi); // now build the query using only the attributes and the bounding // box needed Query q = new Query(schema.getTypeName()); q.setFilter(filter); // now, if a definition query has been established for this layer, // be sure to respect it by combining it with the bounding box one. Query definitionQuery = layer.getQuery(); if (definitionQuery != Query.ALL) { if (q == Query.ALL) { q = (Query) definitionQuery; } else { q = (Query) DataUtilities.mixQueries(definitionQuery, q, "KMLEncoder"); } } // handle startIndex requested by client query q.setStartIndex(definitionQuery.getStartIndex()); // check the regionating strategy RegionatingStrategy regionatingStrategy = null; String stratname = (String) mapContent.getRequest().getFormatOptions().get("regionateBy"); if (("auto").equals(stratname)) { Catalog catalog = wms.getGeoServer().getCatalog(); Name name = layer.getFeatureSource().getName(); stratname = catalog .getFeatureTypeByName(name) .getMetadata() .get("kml.regionateStrategy", String.class); if (stratname == null || "".equals(stratname)) { stratname = "best_guess"; LOGGER.log( Level.FINE, "No default regionating strategy has been configured in " + name + "; using automatic best-guess strategy."); } } if (stratname != null) { regionatingStrategy = findStrategyByName(stratname); // if a strategy was specified but we did not find it, let the user // know if (regionatingStrategy == null) throw new ServiceException("Unknown regionating strategy " + stratname); } // try to load less features by leveraging regionating strategy and the // SLD Filter regionatingFilter = Filter.INCLUDE; if (regionatingStrategy != null) regionatingFilter = regionatingStrategy.getFilter(mapContent, layer); Filter ruleFilter = summarizeRuleFilters( getLayerRules(featureSource.getSchema(), layer.getStyle()), scaleDenominator); Filter finalFilter = joinFilters(q.getFilter(), ruleFilter, regionatingFilter); if (finalFilter == Filter.EXCLUDE) { // if we don't have any feature to return return null; } q.setFilter(finalFilter); // make sure we output in 4326 since that's what KML mandates CoordinateReferenceSystem wgs84; try { wgs84 = CRS.decode("EPSG:4326"); } catch (Exception e) { throw new RuntimeException( "Cannot decode EPSG:4326, the CRS subsystem must be badly broken..."); } if (sourceCrs != null && !CRS.equalsIgnoreMetadata(wgs84, sourceCrs)) { return new ReprojectFeatureResults(featureSource.getFeatures(q), wgs84); } return featureSource.getFeatures(q); }
@Override public void setVisible(boolean visible) { super.setVisible(visible); if (_myLayer != null) _myLayer.setVisible(visible); }