/** * Creates a image of the WFS layer's data * * @return image */ private BufferedImage draw() { MapContent content = new MapContent(); MapViewport viewport = new MapViewport(); CoordinateReferenceSystem crs = location.getCrs(); ReferencedEnvelope bounds = location.getEnvelope(); Rectangle screenArea; if (isTile && bufferSize != 0.0d) { double width = (location.getRight() - location.getLeft()) / 2 * bufferSize; double height = (location.getTop() - location.getBottom()) / 2 * bufferSize; bounds = location.createEnlargedEnvelope(width, height); screenArea = new Rectangle(0, 0, bufferedImageWidth, bufferedImageHeight); } else { screenArea = new Rectangle(0, 0, imageWidth, imageHeight); // image size } viewport.setCoordinateReferenceSystem(crs); viewport.setScreenArea(screenArea); viewport.setBounds(bounds); viewport.setMatchingAspectRatio(true); if (features.size() > 0) { Layer featureLayer = new FeatureLayer(features, style); content.addLayer(featureLayer); } content.setViewport(viewport); return saveImage(content); }
private static void constructMapUI(final File shapefile) { JMapFrame frame; MapContent map = new MapContent(); FileDataStore dataStore; SimpleFeatureSource shapefileSource; try { dataStore = FileDataStoreFinder.getDataStore(shapefile); shapefileSource = dataStore.getFeatureSource(); } catch (IOException e) { e.printStackTrace(); return; } Style shpStyle = SLD.createPolygonStyle(Color.RED, null, 0.0f); Layer shpLayer = new FeatureLayer(shapefileSource, shpStyle); map.addLayer(shpLayer); frame = new JMapFrame(map); frame.enableLayerTable(true); frame.setSize(1000, 800); frame.enableStatusBar(true); frame.enableToolBar(true); frame.setTitle("Map Viewer (courtesy of GeoTools"); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); frame.setVisible(true); frame.setDefaultCloseOperation(JMapFrame.HIDE_ON_CLOSE); }
/* * https://osgeo-org.atlassian.net/browse/GEOT-5287 */ @Test public void testEmptyGeometryRendering() throws Exception { MapContent mc = new MapContent(); /* * We simulate reading empty geometries with this properties and mocking the capability to * filter, so that no filter layer is installed over our data and the empty geometry reaches * rendering code. These geometries are in EPSG:32717 because the 0,0 coordinate is in the * pole. */ File dir = new File(TestData.getResource(this, "empty-geom-rendering.properties").toURI()); PropertyDataStore dataStore = new PropertyDataStore(dir.getParentFile()) { @Override protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException { return new PropertyFeatureSource(entry, Query.ALL) { @Override protected boolean canFilter() { return true; } }; } }; /* * Set up the rendering of previous empty geometry */ StyleBuilder sb = new StyleBuilder(); Style style = sb.createStyle(sb.createPolygonSymbolizer()); Layer layer = new FeatureLayer(dataStore.getFeatureSource("empty-geom-rendering"), style); mc.addLayer(layer); StreamingRenderer sr = new StreamingRenderer(); sr.setMapContent(mc); BufferedImage img = new BufferedImage(40, 40, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = img.createGraphics(); Rectangle paintArea = new Rectangle(40, 40); // An EPSG:8357 extent on the EPSG:32717 area of application. double minx = -8929252.1; double maxx = -8708634.6; double miny = -491855.7; double maxy = -271204.3; ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope( new Rectangle2D.Double(minx, miny, maxx - minx, maxy - miny), CRS.decode("EPSG:3857")); sr.addRenderListener( new RenderListener() { public void featureRenderer(SimpleFeature feature) {} public void errorOccurred(Exception e) { errors++; } }); errors = 0; sr.paint(graphics, paintArea, referencedEnvelope); assertTrue(errors == 0); }
@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)); }
@SuppressWarnings("unchecked") private void paintMe(PaintEvent e) { int width = e.gc.getClipping().width; int height = e.gc.getClipping().height; if (map != null) { // sort out the transforms org.eclipse.swt.graphics.Rectangle paintArea = new org.eclipse.swt.graphics.Rectangle(0, 0, width, height); ReferencedEnvelope mapArea = map.getViewport().getBounds(); setTransforms(mapArea, paintArea); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.setJava2DHints(hints); @SuppressWarnings("rawtypes") Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true)); renderer.setRendererHints(rendererParams); org.eclipse.swt.graphics.Rectangle curPaintArea = e.gc.getClipping(); BufferedImage baseImage = new BufferedImage( curPaintArea.width + 1, curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = baseImage.createGraphics(); g2d.fillRect(0, 0, curPaintArea.width + 1, curPaintArea.height + 1); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // renderer.setContext(context); java.awt.Rectangle awtRectangle = Utils.toAwtRectangle(curPaintArea); final ReferencedEnvelope mapAOI = map.getViewport().getBounds(); renderer.paint(g2d, awtRectangle, mapAOI, getWorldToScreenTransform()); // swtImage.dispose(); if (swtImage != null && !swtImage.isDisposed()) { swtImage.dispose(); swtImage = null; } swtImage = new Image( canvas.getDisplay(), awtToSwt(baseImage, curPaintArea.width + 1, curPaintArea.height + 1)); // org.eclipse.swt.graphics.Image image = new // org.eclipse.swt.graphics.Image( // e.display, convertToSWT(tmpImage)); e.gc.drawImage(swtImage, 0, 0); } double y2 = Math.random() * 120d; e.gc.drawLine(20, 40, 80, (int) y2); };
@Test public void testEventAfterDrawing() throws Exception { // build map context MapContent mc = new MapContent(); mc.addLayer(new FeatureLayer(createLineCollection(), createLineStyle())); // build projected envelope to work with (small one around the area of // validity of utm zone 1, which being a Gauss projection is a vertical // slice parallel to the central meridian, -177°) ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180, -170, 20, 40), DefaultGeographicCRS.WGS84); CoordinateReferenceSystem utm1N = CRS.decode("EPSG:32601"); ReferencedEnvelope reUtm = reWgs.transform(utm1N, true); BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR); // setup the renderer and listen for errors final AtomicInteger commandsCount = new AtomicInteger(0); final BlockingQueue<RenderingRequest> queue = new ArrayBlockingQueue<RenderingRequest>(10) { @Override public void put(RenderingRequest e) throws InterruptedException { commandsCount.incrementAndGet(); super.put(e); } }; StreamingRenderer sr = new StreamingRenderer() { @Override protected BlockingQueue<RenderingRequest> getRequestsQueue() { return queue; } }; sr.setMapContent(mc); sr.addRenderListener( new RenderListener() { public void featureRenderer(SimpleFeature feature) { assertTrue(commandsCount.get() > 0); features++; } public void errorOccurred(Exception e) { errors++; } }); errors = 0; features = 0; sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200), reUtm); // we should get errors since there are two features that cannot be // projected but the renderer itself should not throw exceptions assertTrue(errors > 0); }
public void selectFeatures(int x, int y) { int pixelDelta = 2; LatLon clickUL = Main.map.mapView.getLatLon(x - pixelDelta, y - pixelDelta); LatLon clickLR = Main.map.mapView.getLatLon(x + pixelDelta, y + pixelDelta); Envelope envelope = new Envelope( Math.min(clickUL.lon(), clickLR.lon()), Math.max(clickUL.lon(), clickLR.lon()), Math.min(clickUL.lat(), clickLR.lat()), Math.max(clickUL.lat(), clickLR.lat())); ReferencedEnvelope mapArea = new ReferencedEnvelope(envelope, crsOSMI); Intersects filter = ff.intersects(ff.property("msGeometry"), ff.literal(mapArea)); // // Select features in all layers // content.layers().clear(); // Iterate through features and build a list that intersects the above // envelope for (int idx = 0; idx < arrFeatures.size(); ++idx) { OSMIFeatureTracker tracker = arrFeatures.get(idx); FeatureCollection<SimpleFeatureType, SimpleFeature> features = tracker.getFeatures(); SimpleFeatureSource tempfs = DataUtilities.source(features); FeatureCollection<SimpleFeatureType, SimpleFeature> selectedFeatures; try { selectedFeatures = tempfs.getFeatures(filter); Set<FeatureId> IDs = new HashSet<>(); try (FeatureIterator<SimpleFeature> iter = selectedFeatures.features()) { Main.info("Selected features " + selectedFeatures.size()); while (iter.hasNext()) { SimpleFeature feature = iter.next(); IDs.add(feature.getIdentifier()); } } geometryType = selectGeomType.get(idx + layerOffset); Style style = createDefaultStyle(idx + layerOffset, IDs); content.addLayer(new FeatureLayer(features, style)); } catch (IOException e) { Main.error(e); } } bIsChanged = true; }
/** * @param wfsClient * @throws NoSuchAuthorityCodeException * @throws FactoryException * @throws IOException * @throws IndexOutOfBoundsException * @throws ParseException */ public OsmInspectorLayer(GeoFabrikWFSClient wfsClient, ProgressMonitor monitor) throws NoSuchAuthorityCodeException, FactoryException, IOException, IndexOutOfBoundsException, ParseException { super("OsmInspector"); arrFeatures = new ArrayList<>(); osmiBugInfo = new LinkedHashMap<>(); selectGeomType = new ArrayList<>(); // Step 3 - discovery; enhance to iterate over all types with bounds String typeNames[] = wfsClient.getTypeNames(); renderer = new StreamingRenderer(); CRS.decode(Main.getProjection().toCode()); crsOSMI = CRS.decode("EPSG:4326"); content = new MapContent(crsOSMI); selectGeomType.add(GeomType.POINT); for (int idx = 1; idx < typeNames.length; ++idx) { String typeName = typeNames[idx]; Set<FeatureId> selectedFeatures = new HashSet<>(); FeatureCollection<SimpleFeatureType, SimpleFeature> features = wfsClient.getFeatures(typeName, monitor); setGeometry(selectGeomType, typeName); Main.info("Osm Inspector Features size: " + features.size()); Style style = createDefaultStyle(idx, selectedFeatures); OSMIFeatureTracker tracker = new OSMIFeatureTracker(features); arrFeatures.add(tracker); FeatureIterator<SimpleFeature> it = tracker.getFeatures().features(); while (it.hasNext()) { BugInfo theInfo = new BugInfo(it.next(), osmiBugInfo.size()); osmiBugInfo.put(theInfo, theInfo.bugId); } content.addLayer(new FeatureLayer(tracker.getFeatures(), style)); } osmiIndex = new BugIndex(osmiBugInfo); content.setTitle("Osm Inspector Errors"); renderer.setMapContent(content); bIsChanged = true; // finally initialize the dialog dialog = new OsmInspectorDialog(this); this.updateView(); }
/** * @param wfsClient * @throws NoSuchAuthorityCodeException * @throws FactoryException * @throws IOException * @throws ParseException * @throws NoSuchElementException * @throws IndexOutOfBoundsException */ public void loadFeatures(GeoFabrikWFSClient wfsClient) throws NoSuchAuthorityCodeException, FactoryException, IOException, IndexOutOfBoundsException, NoSuchElementException, ParseException { String typeNames[] = wfsClient.getTypeNames(); content.layers().clear(); selectGeomType.clear(); selectGeomType.add(GeomType.POINT); ProgressMonitor monitor = new ProgressMonitor(Main.map.mapView, "Loading features", "", 0, 100); for (int idx = 1; idx < typeNames.length; ++idx) { String typeName = typeNames[idx]; Set<FeatureId> selectedFeatures = new HashSet<>(); monitor.setProgress(100 / typeNames.length * idx); FeatureCollection<SimpleFeatureType, SimpleFeature> features = wfsClient.getFeatures(typeName, monitor); setGeometry(selectGeomType, typeName); Main.info("Osm Inspector Features size: " + features.size()); OSMIFeatureTracker tracker = arrFeatures.get(idx - layerOffset); tracker.mergeFeatures(features); FeatureIterator<SimpleFeature> it = tracker.getFeatures().features(); while (it.hasNext()) { BugInfo theInfo = new BugInfo(it.next(), osmiBugInfo.size()); if (!osmiBugInfo.keySet().contains(theInfo)) { osmiBugInfo.put(theInfo, theInfo.bugId); } } Style style = createDefaultStyle(idx, selectedFeatures); content.addLayer(new FeatureLayer(tracker.getFeatures(), style)); } osmiIndex.append(osmiBugInfo); monitor.setProgress(100); monitor.close(); bIsChanged = true; // dialog.updateDialog(this); dialog.refreshModel(); // dialog.updateNextPrevAction(this); this.updateView(); }
// public void savePDF(){ // Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize()); // Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); // //rotate if we need landscape // Document document = new Document(pageSize); // // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); // document.open(); // Graphics2D graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight()); // // // call your GTRenderer here // GTRenderer draw = new StreamingRenderer(); // draw.setMapContent(mapContent); // // draw.paint(graphics, outputArea, mapContent.getLayerBounds() ); // // // cleanup // graphics.dispose(); // // //cleanup // document.close(); // writer.close(); // } public void saveImage(final MapContent map, final String file, final int imageWidth) { GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); Rectangle imageBounds = null; ReferencedEnvelope mapBounds = null; try { mapBounds = map.getMaxBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); } catch (Exception e) { // failed to access mapContent layers throw new RuntimeException(e); } BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); Graphics2D gr = image.createGraphics(); gr.setPaint(Color.WHITE); gr.fill(imageBounds); try { renderer.paint(gr, imageBounds, mapBounds); File fileToSave = new File(file); ImageIO.write(image, "jpeg", fileToSave); } catch (Exception e) { e.printStackTrace(); } }
/** * 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); } }
/** * Gets the full extent of map context's layers. The only reason this method is defined is to * avoid having try-catch blocks all through other methods. */ private void setFullExtent() { if (content != null && content.layers().size() > 0) { try { fullExtent = content.getMaxBounds(); /* * Guard agains degenerate envelopes (e.g. empty * map layer or single point feature) */ if (fullExtent == null) { // set arbitrary bounds centred on 0,0 fullExtent = worldEnvelope(); // new ReferencedEnvelope(-1, 1, -1, 1, // context.getCoordinateReferenceSystem()); } // else { // double w = fullExtent.getWidth(); // double h = fullExtent.getHeight(); // double x = fullExtent.getMinimum(0); // double y = fullExtent.getMinimum(1); // // double xmin = x; // double xmax = x + w; // if (w <= 0.0) { // xmin = x - 1.0; // xmax = x + 1.0; // } // // double ymin = y; // double ymax = y + h; // if (h <= 0.0) { // ymin = y - 1.0; // ymax = y + 1.0; // } // // fullExtent = new ReferencedEnvelope(xmin, xmax, ymin, ymax, // context.getCoordinateReferenceSystem()); // } } catch (Exception ex) { throw new IllegalStateException(ex); } } else { fullExtent = null; } }
/** * Internal initializer of the control. It starts up the map context, renderer and sets the * Reference System based in the SRID. * * @param srid * @throws InitializeMapException */ private void initialize(int srid) throws InitializeMapException { MapContent content = new MapContent(); try { content .getViewport() .setCoordinateReferenceSystem(this.generateCoordinateReferenceSystem(srid)); } catch (FactoryException ex) { throw new InitializeMapException( Messaging.Ids.MAPCONTROL_MAPCONTEXT_WITHOUT_SRID_ERROR.toString(), ex); } if (content.getCoordinateReferenceSystem() == null) { throw new InitializeMapException( Messaging.Ids.MAPCONTROL_MAPCONTEXT_WITHOUT_SRID_ERROR.toString(), null); } this.srid = srid; this.setMapContent(content); }
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); } } }
@Test public void testRepeatedEnvelopeExpansion() throws Exception { final List<Filter> filters = new ArrayList<Filter>(); SimpleFeatureSource testSource = new CollectionFeatureSource(createLineCollection()) { @Override public SimpleFeatureCollection getFeatures(Query query) { filters.add(query.getFilter()); return super.getFeatures(query); } }; StyleBuilder sb = new StyleBuilder(); Style style20 = sb.createStyle(sb.createLineSymbolizer(20)); Style style10 = sb.createStyle(sb.createLineSymbolizer(10)); MapContent mc = new MapContent(); mc.addLayer(new FeatureLayer(testSource, style20)); mc.addLayer(new FeatureLayer(testSource, style10)); StreamingRenderer sr = new StreamingRenderer(); sr.setMapContent(mc); BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = bi.createGraphics(); sr.paint( graphics, new Rectangle(0, 0, 100, 100), new ReferencedEnvelope(0, 100, 0, 100, DefaultGeographicCRS.WGS84)); graphics.dispose(); System.out.println(filters); assertEquals(2, filters.size()); Filter f1 = filters.get(0); assertTrue(f1 instanceof BBOX); BoundingBox bbox1 = ((BBOX) f1).getBounds(); ReferencedEnvelope expected = new ReferencedEnvelope(-11, 111, -11, 111, DefaultGeographicCRS.WGS84); assertEquals(expected, bbox1); Filter f2 = filters.get(1); assertTrue(f2 instanceof BBOX); BoundingBox bbox2 = ((BBOX) f2).getBounds(); assertEquals(new ReferencedEnvelope(-6, 106, -6, 106, DefaultGeographicCRS.WGS84), bbox2); }
/** * Test that we don't have the geometry added twice by StreamingRenderer#findStyleAttributes when * geofence is filtering a layer. * * @throws Exception */ @Test public void testFindLineStyleAttributeWithAddedFilter() throws Exception { final List<Filter> filters = new ArrayList<Filter>(); SimpleFeatureSource testSource = new CollectionFeatureSource(createLineCollection()) { @Override public SimpleFeatureCollection getFeatures(Query query) { filters.add(query.getFilter()); return super.getFeatures(query); } }; Style style = createPointStyle(); MapContent mc = new MapContent(); FeatureLayer layer = new FeatureLayer(testSource, style); mc.addLayer(layer); StreamingRenderer sr = new StreamingRenderer(); sr.setMapContent(mc); ReferencedEnvelope envelope = new ReferencedEnvelope(0, 100, 0, 100, DefaultGeographicCRS.WGS84); // simulate geofence adding a bbox BBOX bbox = StreamingRenderer.filterFactory.bbox("", 30, 60, 30, 60, "WGS84"); StyleFactoryImpl sf = new StyleFactoryImpl(); Rule bboxRule = sf.createRule( new Symbolizer[0], new DescriptionImpl(), new Graphic[0], "bbox", bbox, false, 1e12, 0); style.featureTypeStyles().get(0).rules().add(bboxRule); BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = bi.createGraphics(); try { sr.paint(graphics, new Rectangle(5, 5, 7, 7), envelope); } finally { graphics.dispose(); } // must have only one bbox, not two assertEquals(1, filters.size()); assertEquals(FastBBOX.class, filters.get(0).getClass()); }
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); } } }
private void testTransformWithQuery(boolean invert) throws IOException, URISyntaxException, CQLException, NoSuchAuthorityCodeException, FactoryException, Exception { // grab the style Style style = RendererBaseTest.loadStyle( this, invert ? "attributeRename.sld" : "attributeRenameNoInvert.sld"); // grab the data File property = new File(TestData.getResource(this, "point.properties").toURI()); PropertyDataStore ds = new PropertyDataStore(property.getParentFile()); FeatureSource fs = ds.getFeatureSource("point"); // prepare a feature layer with a query and the rendering tx FeatureLayer layer = new FeatureLayer(fs, style); layer.setQuery(new Query(null, CQL.toFilter("id > 5"))); // render it MapContent mc = new MapContent(); mc.addLayer(layer); StreamingRenderer renderer = new StreamingRenderer(); final AtomicInteger counter = new AtomicInteger(); renderer.addRenderListener( new RenderListener() { @Override public void featureRenderer(SimpleFeature feature) { counter.incrementAndGet(); } @Override public void errorOccurred(Exception e) {} }); renderer.setMapContent(mc); ReferencedEnvelope re = new ReferencedEnvelope(0, 12, 0, 12, CRS.decode("EPSG:4326")); BufferedImage image = RendererBaseTest.showRender("Lines with circle stroke", renderer, TIME, re); // if everything went fine we'll have a single red dot in the middle, and we rendered // just one feature assertEquals(1, counter.get()); assertEquals(Color.RED, getPixelColor(image, image.getWidth() / 2, image.getHeight() / 2)); }
/** The constructor. */ public ViewTest() { // Create a map content and add our shapefile to it map = new MapContent(); map.setTitle("simple map content"); // hey, try for an image aswell String path = "/Users/ian/Desktop/ukrasterchart/2_BRITISH_ISLES.tif"; File chartFile = new File(path); if (!chartFile.exists()) System.err.println("CANNOT FILE THE CHART FILE!!!"); WorldImageFormat format = new WorldImageFormat(); AbstractGridCoverage2DReader tiffReader = format.getReader(chartFile); if (tiffReader != null) { StyleFactoryImpl sf = new StyleFactoryImpl(); RasterSymbolizer symbolizer = sf.getDefaultRasterSymbolizer(); Style defaultStyle = SLD.wrapSymbolizers(symbolizer); GeneralParameterValue[] params = null; GridReaderLayer res = new GridReaderLayer(tiffReader, defaultStyle, params); map.addLayer(res); } try { URL url = GtActivator.getDefault().getBundle().getEntry("data/50m_admin_0_countries.shp"); String filePath = FileLocator.resolve(url).getFile(); File file = new File(filePath); if (!file.exists()) System.err.println("can't find file!!!"); FileDataStore store = FileDataStoreFinder.getDataStore(file); if (store != null) { SimpleFeatureSource featureSource = store.getFeatureSource(); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(featureSource, style); map.addLayer(layer); } } catch (IOException e) { } // }
public void fit() throws Exception { MapContent generalMapContext = getGeneralMapContext(); Dimension size = getSize(); Envelope projectedBounds = generalMapContext.getMaxBounds(); double destWidth = projectedBounds.getWidth(); double destHeight = projectedBounds.getHeight(); Coordinate centre = projectedBounds.centre(); Point2D.Double screenLT = awtScreen2Cartesian(new Point(0, 0)); Point2D.Double screenBR = awtScreen2Cartesian(new Point(size.width, size.height)); double srcWidth = screenBR.x - screenLT.x; double srcHeight = screenBR.y - screenLT.y; double sx = srcWidth / destWidth; double sy = srcHeight / destHeight; double coef = Math.min(sx, sy); coef = snapScale(coef); scaleView(coef, coef, false); Point2D.Double projectedScreenCenter = screen2Cartesian(new Point(0, 0)); translateView(projectedScreenCenter.x - centre.x, projectedScreenCenter.y - centre.y, true); repaint(); }
/** 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; }
public Map sectionSigns(DirectPosition2D eventCoords) { Point2D eventPoint = new DirectPosition2D(); eventPoint.setLocation(eventCoords); if (eventCoords != null) { try { AffineTransform transform_affine = map.getViewport().getWorldToScreen(); transform_affine.transform(eventPoint, eventPoint); } catch (Exception e) { e.printStackTrace(); } } Map result = new HashMap(); for (Iterator it1 = signsdb.keySet().iterator(); it1.hasNext(); ) { SimpleFeature feature = (SimpleFeature) it1.next(); StructOffset offset = (StructOffset) signsdb.get(feature); int width = 60, height = 40; Point point = (Point) feature.getAttribute("the_geom"); DirectPosition2D geoCoords = new DirectPosition2D(point.getX(), point.getY()); // 经纬度坐标转换为屏幕坐标 MathTransform transform_math; try { transform_math = CRS.findMathTransform( DefaultGeographicCRS.WGS84, map.getViewport().getCoordinateReferenceSystem(), true); transform_math.transform(geoCoords, geoCoords); AffineTransform transform_affine = map.getViewport().getWorldToScreen(); transform_affine.transform(geoCoords, geoCoords); int signx = (int) (geoCoords.x + offset.getX() + offsetX); int signy = (int) (geoCoords.y + offset.getY() + offsetY); // System.out.println(signsCoords.x+":"+signsCoords.y); if (inSection(signx, signy, width, height, (DirectPosition2D) eventPoint)) { result.put(feature.getID(), feature.getID()); } } catch (Exception e) { } } return result; }
/** Reset the map area to include the full extent of all layers and redraw the display */ public void reset() { if (fullExtent == null) { setFullExtent(); } try { fullExtent = new ReferencedEnvelope(CRS.transform(fullExtent, content.getCoordinateReferenceSystem())); } catch (Exception e) { e.printStackTrace(); } setDisplayArea(fullExtent); }
@Test public void testTransformReproject() throws Exception { // grab the style Style style = RendererBaseTest.loadStyle(this, "reproject-rt.sld"); // grab the data File property = new File(TestData.getResource(this, "point.properties").toURI()); PropertyDataStore ds = new PropertyDataStore(property.getParentFile()); FeatureSource fs = ds.getFeatureSource("point"); // prepare a feature layer with a query and the rendering tx FeatureLayer layer = new FeatureLayer(fs, style); // prepare a bbox in UTM-32N ReferencedEnvelope reWgs84 = new ReferencedEnvelope(0, 12, 0, 12, CRS.decode("EPSG:4326")); ReferencedEnvelope reUTM32N = reWgs84.transform(CRS.decode("EPSG:3857"), true); // render it MapContent mc = new MapContent(); mc.addLayer(layer); StreamingRenderer renderer = new StreamingRenderer(); final AtomicInteger counter = new AtomicInteger(); renderer.addRenderListener( new RenderListener() { @Override public void featureRenderer(SimpleFeature feature) { counter.incrementAndGet(); } @Override public void errorOccurred(Exception e) {} }); renderer.setMapContent(mc); BufferedImage image = RendererBaseTest.showRender("Lines with circle stroke", renderer, TIME, reUTM32N); // if everything went fine we rendered all the features assertEquals(10, counter.get()); assertEquals(Color.RED, getPixelColor(image, image.getWidth() / 2, image.getHeight() / 2)); }
public void saveNewImage(MapContent map, String file) { GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); System.out.println("line 139"); Rectangle imageBounds = null; try { ReferencedEnvelope mapBounds = map.getMaxBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); int imageWidth = 600; imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); } catch (Exception e) { } System.out.println("line 151"); // Rectangle imageSize = new Rectangle(600,600); BufferedImage image = new BufferedImage( imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); // darker red fill Graphics2D gr = image.createGraphics(); gr.setPaint(Color.WHITE); gr.fill(imageBounds); try { System.out.println("line 161"); renderer.paint(gr, imageBounds, map.getMaxBounds()); System.out.println("line 163"); File fileToSave = new File(file); System.out.println("line 166"); ImageIO.write(image, "jpeg", fileToSave); System.out.println("line 168"); } catch (IOException e) { } }
/** * Draws map content data into image * * @param content * @return image */ private BufferedImage saveImage(MapContent content) { BufferedImage image; if (isTile && bufferSize != 0.0d) { image = new BufferedImage(bufferedImageWidth, bufferedImageHeight, BufferedImage.TYPE_4BYTE_ABGR); } else { image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR); } GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(content); Graphics2D g = (Graphics2D) image.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (isTile && bufferSize != 0.0d) { renderer.paint( g, new Rectangle(bufferedImageWidth, bufferedImageHeight), content.getViewport().getBounds()); try { image = image.getSubimage( (int) (imageWidth * bufferSize) / 2, (int) (imageWidth * bufferSize) / 2, imageWidth, imageHeight); } catch (Exception e) { log.error(e, "Image cropping failed"); } } else { renderer.paint(g, new Rectangle(imageWidth, imageHeight), content.getViewport().getBounds()); } content.dispose(); return image; }
/** * Called after the base image has been dragged. Sets the new map area and transforms * * @param env the display area (world coordinates) prior to the image being moved * @param paintArea the current drawing area (screen units) */ private void afterImageMove() { final ReferencedEnvelope env = content.getViewport().getBounds(); if (env == null) return; int dx = imageOrigin.x; int dy = imageOrigin.y; DirectPosition2D newPos = new DirectPosition2D(dx, dy); screenToWorld.transform(newPos, newPos); env.translate(env.getMinimum(0) - newPos.x, env.getMaximum(1) - newPos.y); doSetDisplayArea(env); imageOrigin.setLocation(0, 0); redrawBaseImage = true; }
@Test public void testTransformNullCoverage() throws Exception { Style style = RendererBaseTest.loadStyle(this, "coverageCenter.sld"); GridCoverage2DReader reader = new AbstractGridCoverage2DReader() { @Override public Format getFormat() { return null; } @Override public GridCoverage2D read(GeneralParameterValue[] parameters) throws IllegalArgumentException, IOException { // we return null on purpose, simulating a reader queried outside of its area, or // on a dimension value it does not have return null; } }; MapContent mc = new MapContent(); mc.addLayer(new GridReaderLayer(reader, style)); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mc); ReferencedEnvelope re = new ReferencedEnvelope(-70, 70, -160, 160, CRS.decode("EPSG:4326")); BufferedImage image = RendererBaseTest.showRender("Transformation with null input", renderer, TIME, re); // full white, no NPE double[] minimums = new ImageWorker(image).getMinimums(); assertEquals(255, minimums[0], 0d); assertEquals(255, minimums[1], 0d); assertEquals(255, minimums[2], 0d); assertEquals(255, minimums[3], 0d); }
/** * Helper method for {@linkplain #setDisplayArea} which is also called by other methods that want * to set the display area without provoking repainting of the display * * @param envelope requested display area */ private void doSetDisplayArea(Envelope envelope) { assert (content != null && curPaintArea != null && !curPaintArea.isEmpty()); if (equalsFullExtent(envelope)) { setTransforms(fullExtent, curPaintArea); } else { setTransforms(envelope, curPaintArea); } ReferencedEnvelope adjustedEnvelope = getDisplayArea(); content.getViewport().setBounds(adjustedEnvelope); MapPaneEvent ev = new MapPaneEvent(this, MapPaneEvent.Type.DISPLAY_AREA_CHANGED); publishEvent(ev); }
/** Called when a map layer has been removed */ public void layerRemoved(MapLayerListEvent event) { Layer layer = event.getElement(); if (layerTable != null) { layerTable.onRemoveLayer(layer); } redrawBaseImage = true; if (content.layers().size() == 0) { clearFields(); } else { setFullExtent(); } if (!isDisposed()) redraw(); }