@Override public BoundingBox getBounds() { // Calculate bounds? // if (bounds == null) { // // Initialize bounds // bounds = new ReferencedEnvelope(getFeatureType().getCoordinateReferenceSystem()); // // Loop over all geometries // for (EFeatureGeometry<Geometry> it : eInternal.getGeometryList(Geometry.class)) { if (!it.isEmpty()) { Geometry g = it.getValue(); if (bounds.isNull()) { bounds.init(g.getEnvelopeInternal()); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } } } return bounds; }
private static ReferencedEnvelope toNativeCrs( final GeneralEnvelope requestedEnvelope, final CoordinateReferenceSystem nativeCRS) throws IllegalArgumentException { ReferencedEnvelope reqEnv = toReferencedEnvelope(requestedEnvelope); if (!CRS.equalsIgnoreMetadata(nativeCRS, reqEnv.getCoordinateReferenceSystem())) { // we're being reprojected. We'll need to reproject reqEnv into // our native coordsys try { // ReferencedEnvelope origReqEnv = reqEnv; reqEnv = reqEnv.transform(nativeCRS, true); } catch (FactoryException fe) { // unable to reproject? throw new IllegalArgumentException( "Unable to find a reprojection from requested " + "coordsys to native coordsys for this request", fe); } catch (TransformException te) { throw new IllegalArgumentException( "Unable to perform reprojection from requested " + "coordsys to native coordsys for this request", te); } } return reqEnv; }
/** * Construct a query based on the state of the user interface controls, and possibly workbecnh. * * @return A catalog query */ Query createQuery() { Query filter = new Query(); filter.text = text.getText(); if (filter.text == null || filter.text.length() == 0) { text.setText("1500 Poydras St, New Orleans, LA"); // $NON-NLS-1$ } filter.bbox = new Envelope(); if (bbox.getSelection()) { // TODO get current editor try { IEditorPart editor = getSite().getPage().getActiveEditor(); Object obj = editor.getEditorInput(); Class mapType = obj.getClass(); Method get = mapType.getMethod("getExtent"); // $NON-NLS-1$ Object value = get.invoke(obj); ReferencedEnvelope world = (ReferencedEnvelope) value; filter.bbox = world.transform(DefaultGeographicCRS.WGS84, true); } catch (Throwable t) { LocationUIPlugin.log("ha ha", t); // $NON-NLS-1$ } } return filter; }
public void testSkipProjectionErrors() throws Exception { // build map context MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84); mapContext.addLayer(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"); System.out.println(CRS.getGeographicBoundingBox(utm1N)); ReferencedEnvelope reUtm = reWgs.transform(utm1N, true); BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR); // setup the renderer and listen for errors StreamingRenderer sr = new StreamingRenderer(); sr.setRendererHints(Collections.singletonMap(sr.OPTIMIZED_DATA_LOADING_KEY, Boolean.FALSE)); sr.setContext(mapContext); sr.addRenderListener( new RenderListener() { public void featureRenderer(SimpleFeature feature) {} public void errorOccurred(Exception e) { e.printStackTrace(); errors++; } }); errors = 0; sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200), reUtm); // we should get two errors since there are two features that cannot be // projected but the renderer itself should not throw exceptions assertEquals(2, errors); }
@Override public ReferencedEnvelope getBounds() { ReferencedEnvelope bounds = super.getBounds(); if (bounds.getCoordinateReferenceSystem() == null) return new ReferencedEnvelope(bounds, GeoImportUtil.getDefaultCRS()); else return bounds; }
@SuppressWarnings("deprecation") private void doOverlayImage(GC gc) { Point2D lowerLeft = new Point2D.Double(overlayEnvelope.getMinX(), overlayEnvelope.getMinY()); worldToScreen.transform(lowerLeft, lowerLeft); Point2D upperRight = new Point2D.Double(overlayEnvelope.getMaxX(), overlayEnvelope.getMaxY()); worldToScreen.transform(upperRight, upperRight); Rectangle bounds = overlayImage.getBounds(); if (overlayDoXor) { gc.setXORMode(true); } gc.drawImage( overlayImage, // 0, // 0, // bounds.width, // bounds.height, // (int) lowerLeft.getX(), // (int) upperRight.getY(), // (int) (upperRight.getX() - lowerLeft.getX()), // (int) Math.abs(upperRight.getY() - lowerLeft.getY()) // ); if (overlayDoXor) { gc.setXORMode(false); } }
/** * Calculate the affine transforms used to convert between world and pixel coordinates. The * calculations here are very basic and assume a cartesian reference system. * * <p>Tne transform is calculated such that {@code envelope} will be centred in the display * * @param envelope the current map extent (world coordinates) * @param paintArea the current map pane extent (screen units) */ private void setTransforms(final Envelope envelope, final Rectangle paintArea) { ReferencedEnvelope refEnv = null; if (envelope != null) { refEnv = new ReferencedEnvelope(envelope); } else { refEnv = worldEnvelope(); // FIXME content.setCoordinateReferenceSystem(DefaultGeographicCRS.WGS84); } java.awt.Rectangle awtPaintArea = Utils.toAwtRectangle(paintArea); double xscale = awtPaintArea.getWidth() / refEnv.getWidth(); double yscale = awtPaintArea.getHeight() / refEnv.getHeight(); double scale = Math.min(xscale, yscale); double xoff = refEnv.getMedian(0) * scale - awtPaintArea.getCenterX(); double yoff = refEnv.getMedian(1) * scale + awtPaintArea.getCenterY(); worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff, yoff); try { screenToWorld = worldToScreen.createInverse(); } catch (NoninvertibleTransformException ex) { ex.printStackTrace(); } }
/** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */ public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader) throws IOException { WFSTransactionState ts = null; if (trans == Transaction.AUTO_COMMIT) { ts = new WFSTransactionState(ds); } else { ts = (WFSTransactionState) trans.getState(ds); } ts.addAction( getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE)); ReferencedEnvelope bounds = null; while (reader.hasNext()) { try { SimpleFeature f = reader.next(); List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors(); for (int i = 0; i < atrs.size(); i++) { if (atrs.get(i) instanceof GeometryDescriptor) { Geometry g = (Geometry) f.getAttribute(i); CoordinateReferenceSystem cs = ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem(); if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); if (g == null) continue; if (bounds == null) { bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } } ts.addAction(getSchema().getTypeName(), new InsertAction(f)); } catch (NoSuchElementException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); } catch (IllegalAttributeException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); } } // Fire a notification. // JE if (bounds == null) { // if bounds are null then send an envelope to say that features were added but // at an unknown location. bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem()); ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } else { ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } if (trans == Transaction.AUTO_COMMIT) { ts.commit(); } }
public void write() throws IOException { if (live == null) { throw new IOException("No current feature to write"); } if (live.equals(origional)) { writeImplementation(origional); } else { writeImplementation(live); if (origional != null) { ReferencedEnvelope bounds = new ReferencedEnvelope(); bounds.include(live.getBounds()); bounds.include(origional.getBounds()); store.listenerManager.fireFeaturesChanged( live.getFeatureType().getTypeName(), Transaction.AUTO_COMMIT, bounds, false); } else { store.listenerManager.fireFeaturesAdded( live.getFeatureType().getTypeName(), Transaction.AUTO_COMMIT, ReferencedEnvelope.reference(live.getBounds()), false); } } origional = null; live = null; }
public static void moveMapTo(OLmaps mp, ShapeValue value) { Coordinate p1 = null, p2 = null; ShapeValue env = new ShapeValue(value.getEnvelope()); try { env = env.transform(Geospace.get().getStraightGeoCRS()); } catch (ThinklabException e2) { throw new ThinklabRuntimeException(e2); } ReferencedEnvelope e = env.getEnvelope(); try { p1 = JTS.transform( new Coordinate(e.getMinX(), e.getMinY()), null, ARIESWebappPlugin.get().geoToGoogleTransform); p2 = JTS.transform( new Coordinate(e.getMaxX(), e.getMaxY()), null, ARIESWebappPlugin.get().geoToGoogleTransform); } catch (TransformException e1) { // shouldn't happen throw new ThinklabRuntimeException(e1); } mp.setBounds(p1.x, p1.y, p2.x, p2.y); }
// 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(); } }
/** @param referencedEnvelope */ private void handleEnvelope( ReferencedEnvelope referencedEnvelope, DimensionInfo timeInfo, ReaderDimensionsAccessor dimensions) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute( "", "srsName", "srsName", "", /* "WGS84(DD)" */ "urn:ogc:def:crs:OGC:1.3:CRS84"); start("wcs:lonLatEnvelope", attributes); final StringBuffer minCP = new StringBuffer(Double.toString(referencedEnvelope.getMinX())) .append(" ") .append(referencedEnvelope.getMinY()); final StringBuffer maxCP = new StringBuffer(Double.toString(referencedEnvelope.getMaxX())) .append(" ") .append(referencedEnvelope.getMaxY()); element("gml:pos", minCP.toString()); element("gml:pos", maxCP.toString()); // are we going to report time? if (timeInfo != null && timeInfo.isEnabled()) { SimpleDateFormat timeFormat = dimensions.getTimeFormat(); element("gml:timePosition", timeFormat.format(dimensions.getMinTime())); element("gml:timePosition", timeFormat.format(dimensions.getMaxTime())); } end("wcs:lonLatEnvelope"); }
public void addZoomLevel(ReferencedEnvelope bbox, int tileWidth, int tileHeight) { List<Grid> list = grids.getModelObject(); final Grid newGrid = new Grid(); if (list.isEmpty()) { BoundingBox extent = new BoundingBox(bbox.getMinX(), bbox.getMinY(), bbox.getMaxX(), bbox.getMaxY()); final int levels = 1; GridSet tmpGridset = GridSetFactory.createGridSet( "stub", SRS.getEPSG4326(), extent, false, levels, 1D, GridSetFactory.DEFAULT_PIXEL_SIZE_METER, tileWidth, tileHeight, false); Grid grid = tmpGridset.getGridLevels()[0]; newGrid.setResolution(grid.getResolution()); newGrid.setScaleDenominator(grid.getScaleDenominator()); } else { Grid prev = list.get(list.size() - 1); newGrid.setResolution(prev.getResolution() / 2); newGrid.setScaleDenominator(prev.getScaleDenominator() / 2); } list.add(newGrid); grids.setModelObject(list); // TileMatrixSetEditor.this.convertInput(); }
public void testImportKMLIndirect() throws Exception { File dir = unpack("kml/sample.zip"); String wsName = getCatalog().getDefaultWorkspace().getName(); DataStoreInfo h2DataStore = createH2DataStore(wsName, "kmltest"); SpatialFile importData = new SpatialFile(new File(dir, "sample.kml")); ImportContext context = importer.createContext(importData, h2DataStore); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); LayerInfo layer = task.getLayer(); ResourceInfo resource = layer.getResource(); assertEquals("Invalid srs", "EPSG:4326", resource.getSRS()); ReferencedEnvelope emptyBounds = new ReferencedEnvelope(); emptyBounds.setToNull(); assertTrue("Unexpected bounding box", emptyBounds.equals(resource.getNativeBoundingBox())); // transform chain to limit characters // otherwise we get a sql exception thrown TransformChain transformChain = task.getTransform(); transformChain.add(new DescriptionLimitingTransform()); importer.run(context); Exception error = task.getError(); if (error != null) { error.printStackTrace(); fail(error.getMessage()); } assertFalse("Bounding box not updated", emptyBounds.equals(resource.getNativeBoundingBox())); FeatureTypeInfo fti = (FeatureTypeInfo) resource; assertEquals("Invalid type name", "sample", fti.getName()); FeatureSource<? extends FeatureType, ? extends Feature> featureSource = fti.getFeatureSource(null, null); assertEquals("Unexpected feature count", 20, featureSource.getCount(Query.ALL)); }
/** * Writes out the current feature. * * @throws IOException * @see org.geotools.data.FeatureWriter#write() */ public void write() throws IOException { // DJB: I modified this so it doesnt throw an error if you // do an update and you didnt actually change anything. // (We do the work) if ((live != null)) { // We have a modification to record! diff.modify(live.getID(), current); ReferencedEnvelope bounds = new ReferencedEnvelope((CoordinateReferenceSystem) null); bounds.include(live.getBounds()); bounds.include(current.getBounds()); fireNotification(FeatureEvent.FEATURES_CHANGED, bounds); live = null; current = null; } else if ((live == null) && (current != null)) { // We have new content to record // diff.add(current.getID(), current); fireNotification( FeatureEvent.FEATURES_ADDED, ReferencedEnvelope.reference(current.getBounds())); current = null; } else { throw new IOException("No feature available to write"); } }
@Override public FeatureIterator getSortedFeatures( GeometryDescriptor geom, ReferencedEnvelope latLongEnv, ReferencedEnvelope nativeEnv, Connection cacheConn) throws Exception { FeatureSource fs = featureType.getFeatureSource(null, null); // build the bbox filter FilterFactory ff = CommonFactoryFinder.getFilterFactory(null); BBOX filter = ff.bbox( geom.getLocalName(), nativeEnv.getMinX(), nativeEnv.getMinY(), nativeEnv.getMaxX(), nativeEnv.getMaxY(), null); // build an optimized query (only the necessary attributes Query q = new Query(); q.setFilter(filter); // TODO: enable this when JTS learns how to compute centroids // without triggering the // generation of Coordinate[] out of the sequences... // q.setHints(new Hints(Hints.JTS_COORDINATE_SEQUENCE_FACTORY, // PackedCoordinateSequenceFactory.class)); q.setPropertyNames(new String[] {geom.getLocalName()}); // return the reader return fs.getFeatures(q).features(); }
public static WorldArea toWorldArea(ReferencedEnvelope bounds) { WorldArea worldArea = new WorldArea( new WorldLocation(bounds.getMaxY(), bounds.getMinX(), 0), new WorldLocation(bounds.getMinY(), bounds.getMaxX(), 0)); return worldArea; }
private void equals(ReferencedEnvelope env, double xmin, double xmax, double ymin, double ymax) { double delta = 0.0000001; assertEquals(xmax, env.getMaxX(), delta); assertEquals(xmin, env.getMinX(), delta); assertEquals(ymax, env.getMaxY(), delta); assertEquals(ymin, env.getMinY(), delta); }
/** * Align given bounds with square size and expand by given fraction * * @param bounds * @param size * @return */ private ReferencedEnvelope align(ReferencedEnvelope bounds, double size, double expand) { bounds = new ReferencedEnvelope(bounds); bounds.expandBy(expand * size); double x = offset(bounds.getLowerCorner(), 0, size); double y = offset(bounds.getLowerCorner(), 1, size); bounds.translate(-x, -y); return bounds; }
/** * This example shows how to obtain a color. * * @param g * @param monitor * @throws RenderException */ public void render(Graphics2D g, IProgressMonitor monitor) throws RenderException { if (monitor == null) monitor = new NullProgressMonitor(); CsvReader reader = null; try { ILayer layer = getContext().getLayer(); IGeoResource resource = layer.findGeoResource(CSV.class); if (resource == null) return; ReferencedEnvelope bounds = getRenderBounds(); monitor.subTask("connecting"); CSV csv = resource.resolve(CSV.class, null); // LOOK UP STYLE IStyleBlackboard style = layer.getStyleBlackboard(); Color color = (Color) style.get(ColorStyle.ID); // DATA TO WORLD CoordinateReferenceSystem dataCRS = layer.getCRS(); CoordinateReferenceSystem worldCRS = context.getCRS(); MathTransform dataToWorld = CRS.findMathTransform(dataCRS, worldCRS, false); // DRAW FILE monitor.beginTask("csv render", csv.getSize()); reader = csv.reader(); reader.readHeaders(); int nameIndex = reader.getIndex("name"); Coordinate worldLocation = new Coordinate(); while (reader.readRecord()) { Point point = CSV.getPoint(reader); Coordinate dataLocation = point.getCoordinate(); try { JTS.transform(dataLocation, worldLocation, dataToWorld); } catch (TransformException e) { continue; } if (bounds != null && !bounds.contains(worldLocation)) { continue; // optimize! } java.awt.Point p = getContext().worldToPixel(worldLocation); g.setColor(color); g.fillRect(p.x - 2, p.y - 2, 6, 6); g.setColor(Color.BLACK); String name = reader.get(nameIndex); g.drawString(name, p.x + 15, p.y + 15); monitor.worked(1); if (monitor.isCanceled()) break; } } catch (IOException e) { throw new RenderException(e); // rethrow any exceptions encountered } catch (FactoryException e) { throw new RenderException(e); // rethrow any exceptions encountered } finally { if (reader != null) reader.close(); monitor.done(); } }
/** * Write world image extensions : TFW, PRJ, TAB * * @param request * @param file * @param in * @throws IOException */ private void writeWorldImageExt(WcsReaderRequest request, File file) throws IOException { String baseFilePath = file.getPath().substring(0, file.getPath().lastIndexOf('.')); // Compute image size and image transformed BBOX ReferencedEnvelope transformedBBox; AffineTransform transform; int width = -1; int height = -1; String ext = FileUtils.extension(file); try { final Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(ext.substring(1)); while (readers.hasNext() && width < 0 && height < 0) { ImageInputStream stream = null; try { ImageReader reader = readers.next(); stream = ImageIO.createImageInputStream(file.getAbsoluteFile()); reader.setInput(stream, true, false); width = reader.getWidth(0); height = reader.getHeight(0); break; } catch (Exception e) { width = -1; height = -1; // try next reader; } finally { if (stream != null) { stream.close(); } } } transformedBBox = request.requestBbox.transform(request.responseCRS, true, 10); if (width < 0) { width = (int) Math.round(transformedBBox.getWidth() / request.crsResolution()); } if (height < 0) { height = (int) Math.round(transformedBBox.getHeight() / request.crsResolution()); } Rectangle imageSize = new Rectangle(width, height); transform = RendererUtilities.worldToScreenTransform(transformedBBox, imageSize); transform.invert(); } catch (Exception e) { throw new ExtractorException(e); } // Generate TFW TAB PRJ files createWorldFile(transform, ext, baseFilePath); createTABFile(transformedBBox, width, height, baseFilePath, ext); createPrjFile(request.responseCRS, baseFilePath); }
/** * @see org.geotools.data.FeatureStore#modifyFeatures(org.geotools.feature.AttributeType[], * java.lang.Object[], org.geotools.filter.Filter) */ public void modifyFeatures(Name[] names, Object[] value, Filter filter2) throws IOException { Filter filter = ds.processFilter(filter2); WFSTransactionState ts = null; if (trans == Transaction.AUTO_COMMIT) { ts = new WFSTransactionState(ds); } else { ts = (WFSTransactionState) trans.getState(ds); } Map<String, Object> props = new HashMap<String, Object>(); ReferencedEnvelope bounds = null; for (int i = 0; i < names.length; i++) { if (names[i] instanceof GeometryDescriptor) { Geometry g = (Geometry) value[i]; CoordinateReferenceSystem cs = ((GeometryDescriptor) names[i]).getCoordinateReferenceSystem(); if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); g.setUserData(cs.getIdentifiers().iterator().next().toString()); if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); // set/expand the bounds that are being changed. if (g == null) continue; if (bounds == null) { bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } props.put(names[i].getLocalPart(), value[i]); } ts.addAction( getSchema().getTypeName(), new UpdateAction(getSchema().getTypeName(), filter, props)); // Fire a notification. // JE if (bounds == null) { // if bounds are null then send an envelope to say that features were modified but // at an unknown location. bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem()); ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } else { ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } if (trans == Transaction.AUTO_COMMIT) { ts.commit(); } }
// private static ReferencedEnvelope calculateOldRequestBoundingBox( // final boolean clientSideReprojection, final Envelope viewportBBox, // final CoordinateReferenceSystem viewportCRS, final List<Layer> wmsLayers, // final boolean[] isFullSizeOut ) throws RenderException { // isFullSizeOut[0] = false; // // Envelope viewportBBox2 = viewportBBox; // if (viewportBBox2 == null) { // viewportBBox2 = new Envelope(-180, 180, -90, 90); // } // // Envelope layersBBox = getLayersBoundingBox(viewportCRS, wmsLayers); // if (layersBBox == null) // try { // return new ReferencedEnvelope(viewportBBox, viewportCRS).transform( // DefaultGeographicCRS.WGS84, true); // } catch (TransformException e1) { // throw (RuntimeException) new RuntimeException(Messages.BasicWMSRenderer2_error) // .initCause(e1); // } catch (FactoryException e1) { // throw (RuntimeException) new RuntimeException(Messages.BasicWMSRenderer2_error) // .initCause(e1); // } // // if (!layersBBox.intersects(viewportBBox2)) // return new ReferencedEnvelope(new Envelope(0, 0, 0, 0), viewportCRS); // // double minx, miny, maxx, maxy; // minx = layersBBox.getMinX(); // maxx = layersBBox.getMaxX(); // miny = layersBBox.getMinY(); // maxy = layersBBox.getMaxY(); // boolean noClipping = false; // // int i = 0; // if (viewportBBox2.getMinX() > minx || noClipping) { // minx = viewportBBox2.getMinX(); // i++; // } // if (viewportBBox2.getMinY() > miny || noClipping) { // miny = viewportBBox2.getMinY(); // i++; // } // if (viewportBBox2.getMaxX() < maxx || noClipping) { // maxx = viewportBBox2.getMaxX(); // i++; // } // if (viewportBBox2.getMaxY() < maxy || noClipping) { // maxy = viewportBBox2.getMaxY(); // i++; // } // // if (i == 4) // isFullSizeOut[0] = true; // // ReferencedEnvelope clippedBBox = new ReferencedEnvelope( // new Envelope(minx, maxx, miny, maxy), viewportCRS); // // if (clientSideReprojection) { // // Convert the clipped bounding box to the request CRS. This is the // // BBox to be used in the request. // try { // String code = findRequestCRS(wmsLayers); // if (code == null) // throw new RenderException( // "Error has occurred in the framework! There is no common CRS in layers in renderer"); // //$NON-NLS-1$ // CoordinateReferenceSystem crs = CRS.decode(code); // // clippedBBox = new ReferencedEnvelope(JTS.transform(clippedBBox, null, CRS // .findMathTransform(viewportCRS, crs, true), 4), crs); // } catch (NoSuchAuthorityCodeException e) { // WMSPlugin.log(e.getLocalizedMessage(), e); // return null; // } catch (FactoryException e) { // WMSPlugin.log(e.getLocalizedMessage(), e); // return null; // } catch (MismatchedDimensionException e) { // WMSPlugin.log(e.getLocalizedMessage(), e); // return null; // } catch (TransformException e) { // e.printStackTrace(); // WMSPlugin.log(e.getLocalizedMessage(), e); // return null; // } // } // // return clippedBBox; // } private static ReferencedEnvelope swapAxis(ReferencedEnvelope envelope) { double min0 = envelope.getLowerCorner().getOrdinate(0); double min1 = envelope.getLowerCorner().getOrdinate(1); double max0 = envelope.getUpperCorner().getOrdinate(0); double max1 = envelope.getUpperCorner().getOrdinate(1); ReferencedEnvelope swap = new ReferencedEnvelope(min1, max1, min0, max0, envelope.getCoordinateReferenceSystem()); return swap; }
/** * Sets up the affine transform. Stolen from liteRenderer code. * * @param mapExtent the map extent * @param width the screen size * @param height * @return a transform that maps from real world coordinates to the screen */ public static AffineTransform worldToScreenTransform( ReferencedEnvelope mapExtent, double width, double height) { // the transformation depends on an x/y ordering, if we have a lat/lon crs swap it CoordinateReferenceSystem crs = mapExtent.getCoordinateReferenceSystem(); boolean swap = crs != null && CRS.getAxisOrder(crs) == AxisOrder.NORTH_EAST; if (swap) { mapExtent = new ReferencedEnvelope( mapExtent.getMinY(), mapExtent.getMaxY(), mapExtent.getMinX(), mapExtent.getMaxX(), null); } double scaleX = width / mapExtent.getWidth(); double scaleY = height / mapExtent.getHeight(); double tx = -mapExtent.getMinX() * scaleX; double ty = (mapExtent.getMinY() * scaleY) + height; AffineTransform at = new AffineTransform(scaleX, 0.0d, 0.0d, -scaleY, tx, ty); // if we swapped concatenate a transform that swaps back if (swap) { at.concatenate(new AffineTransform(0, 1, 1, 0, 0, 0)); } return at; }
/** * Creates the {@link RenderedImage} corresponding to the tile at index {@code tileIdx} and uses a * {@link RenderedImageMapResponse} to encode it into the {@link #getResponseFormat() response * format}. * * @see org.geowebcache.layer.MetaTile#writeTileToStream(int, org.geowebcache.io.Resource) * @see RenderedImageMapResponse#write */ @Override public boolean writeTileToStream(final int tileIdx, Resource target) throws IOException { checkNotNull(metaTileMap, "webMap is not set"); if (!(metaTileMap instanceof RenderedImageMap)) { throw new IllegalArgumentException( "Only RenderedImageMaps are supported so far: " + metaTileMap.getClass().getName()); } final RenderedImageMapResponse mapEncoder; { final GWC mediator = GWC.get(); final Response responseEncoder = mediator.getResponseEncoder(responseFormat, metaTileMap); mapEncoder = (RenderedImageMapResponse) responseEncoder; } RenderedImage tile = metaTileMap.getImage(); WMSMapContent tileContext = metaTileMap.getMapContext(); if (this.tiles.length > 1 || (this.tiles.length == 1 && metaHasGutter())) { final Rectangle tileDim = this.tiles[tileIdx]; tile = createTile(tileDim.x, tileDim.y, tileDim.width, tileDim.height); disposeLater(tile); { final WMSMapContent metaTileContext = metaTileMap.getMapContext(); // do not create tileContext with metaTileContext.getLayers() as the layer list. // It is not needed at this stage and the constructor would force a // MapLayer.getBounds() that might fail tileContext = new WMSMapContent(); tileContext.setRequest(metaTileContext.getRequest()); tileContext.setBgColor(metaTileContext.getBgColor()); tileContext.setMapWidth(tileDim.width); tileContext.setMapHeight(tileDim.height); tileContext.setPalette(metaTileContext.getPalette()); tileContext.setTransparent(tileContext.isTransparent()); long[][] tileIndexes = getTilesGridPositions(); BoundingBox tileBounds = gridSubset.boundsFromIndex(tileIndexes[tileIdx]); ReferencedEnvelope tilebbox = new ReferencedEnvelope(metaTileContext.getCoordinateReferenceSystem()); tilebbox.init( tileBounds.getMinX(), tileBounds.getMaxX(), tileBounds.getMinY(), tileBounds.getMaxY()); tileContext.getViewport().setBounds(tilebbox); } } OutputStream outStream = target.getOutputStream(); try { // call formatImageOuputStream instead of write to avoid disposition of rendered images // when processing a tile from a metatile and instead defer it to this class' dispose() // method mapEncoder.formatImageOutputStream(tile, outStream, tileContext); return true; } finally { outStream.close(); } }
@Test public void getEnvelope2D() { ReferencedEnvelope refEnv = new ReferencedEnvelope(-10, 10, -5, 5, DefaultGeographicCRS.WGS84); Envelope2D env2D = JTS.getEnvelope2D(refEnv, refEnv.getCoordinateReferenceSystem()); CRS.equalsIgnoreMetadata( refEnv.getCoordinateReferenceSystem(), env2D.getCoordinateReferenceSystem()); assertTrue(env2D.boundsEquals(refEnv, 0, 1, TOL)); }
@Override public void onClick() { ExtendedLayerEditor cadastreObjectLayer = getTargetCadastreObjectLayer(); if (cadastreObjectLayer.getFeatureCollection().size() > 0) { ReferencedEnvelope envelope = cadastreObjectLayer.getFeatureCollection().getBounds(); envelope.expandBy(10); this.getMapControl().setDisplayArea(envelope); } super.onClick(); }
@Override public ReferencedEnvelope getBounds() { try { ReferencedEnvelope bounds = featureSource.getBounds(); if (bounds != null) { FeatureType schema = featureSource.getSchema(); CoordinateReferenceSystem schemaCrs = schema.getCoordinateReferenceSystem(); CoordinateReferenceSystem boundsCrs = bounds.getCoordinateReferenceSystem(); if (boundsCrs == null && schemaCrs != null) { LOGGER.warning( "Bounds crs not defined; assuming bounds from schema are correct for " + featureSource); bounds = new ReferencedEnvelope( bounds.getMinX(), bounds.getMaxX(), bounds.getMinY(), bounds.getMaxY(), schemaCrs); } if (boundsCrs != null && schemaCrs != null && !CRS.equalsIgnoreMetadata(boundsCrs, schemaCrs)) { LOGGER.warning( "Bounds crs and schema crs are not consistent; forcing the use of the schema crs so they are consistent"); // bounds = bounds.transform(schemaCrs, true ); bounds = new ReferencedEnvelope( bounds.getMinX(), bounds.getMaxX(), bounds.getMinY(), bounds.getMaxY(), schemaCrs); } return bounds; } } catch (IOException e) { // feature bounds unavailable } CoordinateReferenceSystem crs = featureSource.getSchema().getCoordinateReferenceSystem(); if (crs != null) { // returns the envelope based on the CoordinateReferenceSystem Envelope envelope = CRS.getEnvelope(crs); if (envelope != null) { return new ReferencedEnvelope(envelope); // nice! } else { return new ReferencedEnvelope(crs); // empty bounds } } else { return null; // unknown } }
/** * Computes the aggregated bounds of {@code features}, assuming all of them are in the same CRS */ public ReferencedEnvelope boundsOf(Feature... features) { ReferencedEnvelope bounds = null; for (int i = 0; i < features.length; i++) { Feature f = features[i]; if (bounds == null) { bounds = (ReferencedEnvelope) f.getBounds(); } else { bounds.include(f.getBounds()); } } return bounds; }
@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); }