Java Code Examples for org.geotools.geometry.jts.ReferencedEnvelope

The following are top voted examples for showing how to use org.geotools.geometry.jts.ReferencedEnvelope. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: downloadclient   File: WMSMapSwing.java   Source Code and License 8 votes vote down vote up
/**
 * sets the viewport of the map to the given extend.
 *
 * @param envelope the extend
 */
public void setExtend(ReferencedEnvelope envelope) {
    try {
        envelope = envelope.transform(this.mapContent.getViewport()
                .getCoordinateReferenceSystem(), true);
        double xLength = envelope.getSpan(0);
        xLength = xLength * TEN_PERCENT;
        double yLength = envelope.getSpan(1);
        yLength = yLength * TEN_PERCENT;
        envelope.expandBy(xLength, yLength);
        bboxAction.resetCoordinates();
        mapPane.deleteGraphics();
        mapPane.setDisplayArea(envelope);
    } catch (FactoryException | TransformException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}
 
Example 2
Project: ExpressZip   File: MapModel.java   Source Code and License 8 votes vote down vote up
/**
 * Expands inBounds by multiplying min of inBounds.getWidth and inBounds.getHeight times percent
 * 
 * @param inBounds
 * @param percent
 * @return
 */
public static Bounds expandBounds(Bounds inBounds, String inCRS, double percent) {

	try {
		double ulx = inBounds.getLeft();
		double uly = inBounds.getTop();
		double lrx = inBounds.getRight();
		double lry = inBounds.getBottom();

		CoordinateReferenceSystem theCRS = CRS.decode(inCRS);
		ReferencedEnvelope re = new ReferencedEnvelope(ulx, lrx, lry, uly, theCRS);
		double expandBy = Math.min(re.getHeight(), re.getWidth()) * percent;
		re.expandBy(expandBy);
		return getBounds(re.toBounds(theCRS));

	} catch (Exception e) {
	}

	return null;
}
 
Example 3
Project: timezone   File: TZShapeReader.java   Source Code and License 7 votes vote down vote up
public void read(URL file) throws IOException {
    Map<String, Object> map = new HashMap<>();
    map.put("url", file);


    DataStore dataStore = DataStoreFinder.getDataStore(map);
    String typeName = dataStore.getTypeNames()[0];

    FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);

    FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();

    FeatureIterator<SimpleFeature> features = collection.features();
    int count = 0;
    LOGGER.info("reading world time zones ...");
    while (features.hasNext()) {
        count++;
        SimpleFeature feature = features.next();
        ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(feature.getBounds());
        quadtree.insert(referencedEnvelope,feature);
    }
    LOGGER.info(count + " features read");

}
 
Example 4
Project: geoserver-3d-extension   File: GMLBoxTypeBinding_ISO.java   Source Code and License 7 votes vote down vote up
@Override
public Object parse(ElementInstance instance, Node node, Object value) throws Exception {
    Envelope envelope = (Envelope) super.parse(instance, node, value);

    // handle the box CRS
    CoordinateReferenceSystem crs = this.crs;
    if (node.hasAttribute("srsName")) {
        URI srs = (URI) node.getAttributeValue("srsName");
        crs = CRS.decode(srs.toString());
    }
    
    if(crs != null) {
        return ReferencedEnvelope.create(envelope, crs);
    } else {
        return envelope;
    }
}
 
Example 5
Project: downloadclient   File: WMSMapSwing.java   Source Code and License 7 votes vote down vote up
/**
  * Resizes swing content and centers map.
  * @param width The new content width.
  */
public void resizeSwingContent(double width) {
    try {
        if (width >= mapWidth) {
            double oldWidth = mapPane.getWidth();

            this.mapNode.resize(width - MAP_NODE_MARGIN, mapHeight);
            double scale = mapPane.getWorldToScreenTransform().getScaleX();
            ReferencedEnvelope bounds = mapPane.getDisplayArea();

            double dXScreenCoord = (width - MAP_NODE_MARGIN - oldWidth) / 2;
            double dXWorldCoord = dXScreenCoord / scale;

            bounds.translate(-1 * dXWorldCoord , 0);
            mapPane.setDisplayArea(bounds);
            mapPane.deleteGraphics();
            clearCoordinateDisplay();
        }
    } catch (NullPointerException e) { }
}
 
Example 6
Project: gama   File: VectorLayerHelper.java   Source Code and License 7 votes vote down vote up
private ReferencedEnvelope createSearchEnv(final DirectPosition2D pos, final double radius) {
	final CoordinateReferenceSystem contextCRS = getMapContent().getCoordinateReferenceSystem();
	ReferencedEnvelope env = new ReferencedEnvelope(pos.x - radius, pos.x + radius, pos.y - radius, pos.y + radius,
			contextCRS);
	if (isTransformRequired()) {
		final Layer layer = layerRef.get();
		if (layer != null) {
			final CoordinateReferenceSystem layerCRS = layer.getFeatureSource().getSchema()
					.getCoordinateReferenceSystem();
			try {
				env = env.transform(layerCRS, true);
			} catch (final Exception ex) {
				throw new IllegalStateException(ex);
			}
		}
	}

	return env;
}
 
Example 7
Project: platypus-js   File: MapTilesCache.java   Source Code and License 7 votes vote down vote up
private void calcAoi() throws NoninvertibleTransformException {
    Point2D.Double[] pts = new Point2D.Double[4];
    pts[0] = new Point2D.Double(tileCenter.x - tileHalf, tileCenter.y - tileHalf);
    pts[1] = new Point2D.Double(tileCenter.x + tileHalf, tileCenter.y - tileHalf);
    pts[2] = new Point2D.Double(tileCenter.x - tileHalf, tileCenter.y + tileHalf);
    pts[3] = new Point2D.Double(tileCenter.x + tileHalf, tileCenter.y + tileHalf);
    cartesian2ScreenTransform.inverseTransform(pts[0], pts[0]);
    cartesian2ScreenTransform.inverseTransform(pts[1], pts[1]);
    cartesian2ScreenTransform.inverseTransform(pts[2], pts[2]);
    cartesian2ScreenTransform.inverseTransform(pts[3], pts[3]);
    double x1 = Double.MAX_VALUE;
    double x2 = -Double.MAX_VALUE;
    double y1 = Double.MAX_VALUE;
    double y2 = -Double.MAX_VALUE;
    for (Point2D.Double pt : pts) {
        x1 = Math.min(x1, pt.x);
        y1 = Math.min(y1, pt.y);
        x2 = Math.max(x2, pt.x);
        y2 = Math.max(y2, pt.y);
    }
    tileAoi = new ReferencedEnvelope(x1, x2, y1, y2, mapDisplayContextCrs);
}
 
Example 8
Project: hortonmachine   File: DaoImages.java   Source Code and License 7 votes vote down vote up
/**
 * Get the current data envelope.
 * 
 * @param connection the db connection.
 * @return the envelope.
 * @throws Exception
 */
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception {
    String query = "SELECT min(" + //
            ImageTableFields.COLUMN_LON.getFieldName() + "), max(" + //
            ImageTableFields.COLUMN_LON.getFieldName() + "), min(" + //
            ImageTableFields.COLUMN_LAT.getFieldName() + "), max(" + //
            ImageTableFields.COLUMN_LAT.getFieldName() + ") " + //
            " FROM " + TABLE_IMAGES;
    try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) {
        if (rs.next()) {
            double minX = rs.getDouble(1);
            double maxX = rs.getDouble(2);
            double minY = rs.getDouble(3);
            double maxY = rs.getDouble(4);

            ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84);
            return env;
        }
    }

    return null;
}
 
Example 9
Project: hortonmachine   File: RasterizedSpatialiteLasLayer.java   Source Code and License 7 votes vote down vote up
public RasterizedSpatialiteLasLayer( String title, ASpatialDb db, Integer tileSize, boolean transparentBackground,
        boolean doIntensity ) throws Exception {
    super(makeLevels(title, tileSize, transparentBackground, db, doIntensity));
    String plus = doIntensity ? INTENSITY : ELEVATION;
    this.layerName = title + " " + plus;
    this.setUseTransparentTextures(true);

    try {
        Envelope tableBounds = db.getTableBounds(LasSourcesTable.TABLENAME);
        GeometryColumn spatialiteGeometryColumns = db.getGeometryColumnsForTable(LasCellsTable.TABLENAME);
        CoordinateReferenceSystem dataCrs = CRS.decode("EPSG:" + spatialiteGeometryColumns.srid);
        CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
        ReferencedEnvelope env = new ReferencedEnvelope(tableBounds, dataCrs);
        ReferencedEnvelope envLL = env.transform(targetCRS, true);

        centre = envLL.centre();
    } catch (Exception e) {
        e.printStackTrace();
        centre = CrsUtilities.WORLD.centre();
    }
}
 
Example 10
Project: snap-desktop   File: MosaicFormModel.java   Source Code and License 7 votes vote down vote up
public Product getBoundaryProduct() throws FactoryException, TransformException {
    final CoordinateReferenceSystem mapCRS = getTargetCRS();
    if (mapCRS != null) {
        final ReferencedEnvelope envelope = getTargetEnvelope();
        final Envelope mapEnvelope = envelope.transform(mapCRS, true);

        final double pixelSizeX = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_X);
        final double pixelSizeY = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_Y);
        final int w = MathUtils.floorInt(mapEnvelope.getSpan(0) / pixelSizeX);
        final int h = MathUtils.floorInt(mapEnvelope.getSpan(1) / pixelSizeY);

        final Product product = new Product("mosaic", "MosaicBounds", w, h);
        final GeoCoding geoCoding = new CrsGeoCoding(mapCRS,
                                                     w, h,
                                                     mapEnvelope.getMinimum(0),
                                                     mapEnvelope.getMaximum(1),
                                                     pixelSizeX, pixelSizeY);
        product.setSceneGeoCoding(geoCoding);

        return product;
    }
    return null;
}
 
Example 11
Project: snap-desktop   File: FeatureLayer.java   Source Code and License 7 votes vote down vote up
public FeatureLayer(LayerType layerType, final FeatureCollection<SimpleFeatureType, SimpleFeature> fc,
                    PropertySet configuration) {
    super(layerType, configuration);
    crs = fc.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem();
    if (crs == null) {
        // todo - check me! Why can this happen??? (nf)
        crs = DefaultGeographicCRS.WGS84;
    }
    final ReferencedEnvelope envelope = new ReferencedEnvelope(fc.getBounds(), crs);
    modelBounds = new Rectangle2D.Double(envelope.getMinX(), envelope.getMinY(),
                                         envelope.getWidth(), envelope.getHeight());
    mapContext = new DefaultMapContext(crs);
    final Style style = (Style) configuration.getValue(FeatureLayerType.PROPERTY_NAME_SLD_STYLE);
    mapContext.addLayer(fc, style);
    renderer = new StreamingRenderer();
    workaroundLabelCacheBug();
    style.accept(new RetrievingStyleVisitor());
    renderer.setContext(mapContext);

}
 
Example 12
Project: sumo   File: WorldScreen.java   Source Code and License 6 votes vote down vote up
public static Point2D getWorldtoScreen(double x, double y){
    
    Rectangle imageBounds=null;
    ReferencedEnvelope mapBounds=null;
    try{
//        mapBounds=map.getLayerBounds();
        imageBounds = mapFrame.getBounds();
        int width = (int)imageBounds.getWidth();
        int height = (int)imageBounds.getHeight();
    }catch(Exception e){
        
    } 
    
    
    AffineTransform world2screen =
    RendererUtilities.worldToScreenTransform(mapBounds, imageBounds);
    Point2D pointScreenAbsolute = new Point2D.Double(x, y);
    Point2D pointScreen = world2screen.transform(pointScreenAbsolute, null);
    return pointScreen;
}
 
Example 13
Project: sumo   File: WorldScreen.java   Source Code and License 6 votes vote down vote up
public static Point2D getScreentoWorld(double x, double y) throws Exception {
    Rectangle imageBounds=null;
    ReferencedEnvelope mapBounds=null;
    try{
//        mapBounds=map.getLayerBounds();
        imageBounds = mapFrame.getBounds();
        int width = (int)imageBounds.getWidth();
        int height = (int)imageBounds.getHeight();
    }catch(Exception e){
        
    } 
    
    AffineTransform world2screen =
    RendererUtilities.worldToScreenTransform(mapBounds, imageBounds);
    
    AffineTransform screen2world = world2screen.createInverse();
    Point2D pointScreenAbsolute = new Point2D.Double(x, y);
    Point2D pointScreen = screen2world.transform(pointScreenAbsolute, null); 
    return pointScreen;
}
 
Example 14
Project: ms-gs-plugins   File: BoundsUpdateTransactionListener.java   Source Code and License 6 votes vote down vote up
private void afterTransactionInternal(final TransactionType transaction, boolean committed) {
    log.fine("Detected change to data, updating bounds of affected featuer types and layer groups");
    
    final Map<Name, Collection<ReferencedEnvelope>> byLayerDirtyRegions = getByLayerDirtyRegions(transaction);
    if (byLayerDirtyRegions.isEmpty()) {
        return;
    }
    byLayerDirtyRegions.entrySet().stream().forEach(e->{
        FeatureTypeInfo fti = catalog.getFeatureTypeByName(e.getKey());
        try{
            merge(fti.getNativeBoundingBox(), e.getValue()).ifPresent(dirtyRegion->{
                // Update the feature type
                updateFeatureType(fti, dirtyRegion);
                // Update all the layer groups that use it, directly or indirectly
                StreamSupport.stream(getLayerGroupsFor(fti).spliterator(), false)
                    .forEach(lgi->updateLayerGroup(lgi, dirtyRegion));
            });
        } catch (Exception ex) {
            log.log(Level.WARNING, ex.getMessage(), ex);
            return;
        }
    });
 
}
 
Example 15
Project: ms-gs-plugins   File: BoundsUpdateTransactionListener.java   Source Code and License 6 votes vote down vote up
private Optional<ReferencedEnvelope> merge(final ReferencedEnvelope oldEnv,
        final Collection<ReferencedEnvelope> dirtyList) {
    final CoordinateReferenceSystem declaredCrs = oldEnv.getCoordinateReferenceSystem();
    return dirtyList.stream()
        .map(env->{
            if(env instanceof ReferencedEnvelope3D) {
                return new ReferencedEnvelope(env, CRS.getHorizontalCRS(env.getCoordinateReferenceSystem()));
            } else  {
                return env;
            }
        })
        .map(env->{
            try {
                return env.transform(declaredCrs, true, 1000);
            } catch (TransformException | FactoryException e) {
                throw new RuntimeException("Error while merging bounding boxes",e);
            }
        })
        .reduce((env1, env2)->{ReferencedEnvelope x = new ReferencedEnvelope(env1); x.expandToInclude(env2); return x;});
}
 
Example 16
Project: ms-gs-plugins   File: BoundsUpdateTransactionListenerTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testDataStoreChangeInsert() {
    
    Map<Object, Object> extendedProperties = new HashMap<Object, Object>();
    ReferencedEnvelope affectedBounds = new ReferencedEnvelope(-180, -90, 45, 90, WGS84);
    ReferencedEnvelope oldBounds = new ReferencedEnvelope(-90, 0, 0, 45, WGS84);
    
    EasyMock.expect(catalog.getFeatureTypeByName(featureTypeName1)).andStubReturn(featureType1);
    EasyMock.expect(featureType1.getNativeBoundingBox()).andStubReturn(oldBounds);
    
    EasyMock.replay(catalog, featureType1, featureType2);
    issueInsert(extendedProperties, affectedBounds);
    
    assertThat(extendedProperties, 
            (Matcher)hasEntry(
                    equalTo(BoundsUpdateTransactionListener.FEATURE_TYPE_AFFECTED_MAP),
                    allOf(
                            hasEntry(equalTo(featureTypeName1),
                                contains(affectedBounds))
                            )));
    
    EasyMock.verify(catalog, featureType1, featureType2);
    
}
 
Example 17
Project: ms-gs-plugins   File: BoundsUpdateTransactionListenerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Issues a fake dataStoreChange insert event that affects two tile layers: "theLayer" and
 * "theGroup"
 */
private void issueInsert(Map<Object, Object> extendedProperties,
        ReferencedEnvelope affectedBounds) {
    
    TransactionType transaction = EasyMock.createNiceMock(TransactionType.class);
    EasyMock.expect(transaction.getExtendedProperties()).andStubReturn(extendedProperties);
    
    TransactionEvent event = EasyMock.createNiceMock(TransactionEvent.class);
    
    EasyMock.expect(event.getRequest()).andStubReturn(transaction);
    
    EasyMock.expect(event.getLayerName()).andStubReturn(featureTypeQName1);
    
    InsertElementType insert = EasyMock.createNiceMock(InsertElementType.class);
    
    EasyMock.expect(event.getSource()).andStubReturn(insert);
    EasyMock.expect(event.getType()).andStubReturn(TransactionEventType.PRE_INSERT);
    
    SimpleFeatureCollection affectedFeatures = EasyMock.createNiceMock(SimpleFeatureCollection.class);
    EasyMock.expect(affectedFeatures.getBounds()).andStubReturn(affectedBounds);
    EasyMock.expect(event.getAffectedFeatures()).andStubReturn(affectedFeatures);
    EasyMock.replay(transaction, event, insert, affectedFeatures);
    listener.dataStoreChange(event);
}
 
Example 18
Project: sldeditor   File: RenderPanelImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Render vector map.
 *
 * @param features the results
 * @param imageSize the image size
 * @param style the style
 * @param dpi the dpi
 */
private void renderVectorMap(FeatureSource<SimpleFeatureType, SimpleFeature> features,
        Rectangle imageSize, Style style, int dpi) {
    List<Layer> layerList = new ArrayList<Layer>();
    if (style != null) {
        FeatureLayer featureLayer = new FeatureLayer(features, style);
        layerList.add(featureLayer);
    }

    boolean hasGeometry = false;
    ReferencedEnvelope bounds = null;

    if (features != null) {
        bounds = calculateBounds();

        wmsEnvVarValues.setMapBounds(bounds);

        EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVarValues);

        if (features.getSchema() != null) {
            hasGeometry = (features.getSchema().getGeometryDescriptor() != null);
        }
    }

    internal_renderMap(layerList, bounds, imageSize, hasGeometry, dpi);
}
 
Example 19
Project: sldeditor   File: FieldConfigBoundingBox.java   Source Code and License 6 votes vote down vote up
/**
 * Populate field.
 *
 * @param value the value
 */
@Override
public void populateField(ReferencedEnvelope value) {
    xMinTextField.setText(Double.toString(value.getMinX()));
    xMaxTextField.setText(Double.toString(value.getMaxX()));
    yMinTextField.setText(Double.toString(value.getMinY()));
    yMaxTextField.setText(Double.toString(value.getMaxY()));

    String key = CoordManager.getInstance().getCRSCode(value.getCoordinateReferenceSystem());

    crsComboBox.setSelectValueKey(key);

    UndoManager.getInstance()
            .addUndoEvent(new UndoEvent(this, getFieldId(), oldValueObj, value));
    oldValueObj = value;
}
 
Example 20
Project: sldeditor   File: EnvironmentVariableManagerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for
 * {@link com.sldeditor.filter.v2.envvar.EnvironmentVariableManager#setWMSEnvVarValues(com.sldeditor.filter.v2.envvar.WMSEnvVarValues)}.
 */
@Test
public void testSetWMSEnvVarValues() {
    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(null);

    WMSEnvVarValues wmsEnvVar = new WMSEnvVarValues();

    wmsEnvVar.setImageHeight(42);
    wmsEnvVar.setImageWidth(454);
    Envelope envelope = new Envelope(1.0, 2.0, 50.0, 51.1);
    ReferencedEnvelope mapBounds = ReferencedEnvelope.create(envelope,
            CoordManager.getInstance().getWGS84());
    wmsEnvVar.setMapBounds(mapBounds);

    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVar);

    // Update the values again
    WMSEnvVarValues wmsEnvVar2 = new WMSEnvVarValues();
    wmsEnvVar2.setImageHeight(69);
    wmsEnvVar2.setImageWidth(123);
    Envelope envelope2 = new Envelope(-1.0, -2.0, 50.0, 51.1);
    ReferencedEnvelope mapBounds2 = ReferencedEnvelope.create(envelope2,
            CoordManager.getInstance().getWGS84());
    wmsEnvVar2.setMapBounds(mapBounds2);
    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVar2);
}
 
Example 21
Project: downloadclient   File: WMSMapSwing.java   Source Code and License 6 votes vote down vote up
private void setExtend(Double x1, Double x2, Double y1, Double y2, String
        crs) {
    CoordinateReferenceSystem coordinateReferenceSystem = null;
    try {
        coordinateReferenceSystem = CRS.decode(crs);
        ReferencedEnvelope initExtend =
                new ReferencedEnvelope(x1,
                        x2,
                        y1,
                        y2, coordinateReferenceSystem);
        setExtend(initExtend);
    } catch (FactoryException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

}
 
Example 22
Project: osmgpxinclinecalculator   File: RasterDataSource.java   Source Code and License 6 votes vote down vote up
private void loadImage() throws IOException {
	File file = new File(path);

	GeoTiffReader reader = new GeoTiffReader(file, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
	coverage = (GridCoverage2D) reader.read(null);
	crs = coverage.getCoordinateReferenceSystem();
	env = new ReferencedEnvelope(coverage.getEnvelope2D());

}
 
Example 23
Project: gama   File: GridLayerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Get band values at the given position
 *
 * @param pos
 *            the location to query
 *
 * @param params
 *            not used at present
 *
 * @return a {@code List} of band values; will be empty if {@code pos} was
 *         outside the coverage bounds
 *
 * @throws Exception
 *             if the grid coverage could not be queried
 */
@Override
public List<Number> getInfo(final DirectPosition2D pos, final Object... params) throws Exception {

	final List<Number> list = new ArrayList<Number>();

	if (isValid()) {
		final GridCoverage2D cov = covRef.get();
		if (cov != null) {
			final ReferencedEnvelope env = new ReferencedEnvelope(cov.getEnvelope2D());
			final DirectPosition2D trPos = getTransformed(pos);
			if (env.contains(trPos)) {
				final Object objArray = cov.evaluate(trPos);
				final Number[] bandValues = asNumberArray(objArray);
				if (bandValues != null) {
					for (final Number value : bandValues) {
						list.add(value);
					}
				}
			}
		}
	}

	return list;
}
 
Example 24
Project: gama   File: SwtMapPane.java   Source Code and License 6 votes vote down vote up
public void setCrs(final CoordinateReferenceSystem crs) {
	try {
		// System.out.println(content.layers().size());
		final ReferencedEnvelope rEnv = getDisplayArea();
		// System.out.println(rEnv);

		final CoordinateReferenceSystem sourceCRS = rEnv.getCoordinateReferenceSystem();
		final CoordinateReferenceSystem targetCRS = crs;

		final MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
		final com.vividsolutions.jts.geom.Envelope newJtsEnv = JTS.transform(rEnv, transform);

		final ReferencedEnvelope newEnvelope = new ReferencedEnvelope(newJtsEnv, targetCRS);
		content.getViewport().setBounds(newEnvelope);
		fullExtent = null;
		doSetDisplayArea(newEnvelope);

		// ReferencedEnvelope displayArea =
		getDisplayArea();
		// System.out.println(displayArea);
	} catch (final Exception e) {
		e.printStackTrace();
	}
}
 
Example 25
Project: gama   File: SwtMapPane.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	final int dx = imageOrigin.x;
	final int dy = imageOrigin.y;
	final 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;
}
 
Example 26
Project: gama   File: SwtMapPane.java   Source Code and License 6 votes vote down vote up
/**
 * Define an image that has to be set as overlay.
 * 
 * <p>
 * The image will be scaled to fit into the supplied envelope.
 * 
 * @param overlayImage
 *            the image to overlay.
 * @param overlayEnvelope
 *            the envelope it has to cover.
 * @param overlayDoXor
 *            flag for Xor mode.
 */
public void setOverlay(final Image overlayImage, final ReferencedEnvelope overlayEnvelope,
		final boolean overlayDoXor, final boolean boundsChanged) {
	if (this.overlayImage != null)
		this.overlayImage.dispose();
	this.overlayImage = overlayImage;
	this.overlayEnvelope = overlayEnvelope;
	this.overlayDoXor = overlayDoXor;

	if (boundsChanged || swtImage == null) {
		redrawBaseImage = true;
	} else {
		redrawBaseImage = false;
	}
	if (!isDisposed())
		redraw();
}
 
Example 27
Project: gama   File: DrawShapeAction.java   Source Code and License 6 votes vote down vote up
/**
 * Called when the associated control is activated. Leads to the map pane's cursor tool being set to a PanTool
 * object
 * 
 * @param ev
 *            the event (not used)
 */
@Override
public void run() {
	if (first) {
		getMapPane().getMapContent().addMapBoundsListener(this);
		first = false;
	}

	final Rectangle visibleRect = getMapPane().getVisibleRect();
	final ReferencedEnvelope displayArea = getMapPane().getDisplayArea();
	drawShapes(visibleRect, displayArea, false);

	/*
	 * to switch of drawing, simply do
	 */
	// getMapPane().setOverlay(null, null, false);
	// getMapPane().redraw();
}
 
Example 28
Project: gama   File: GISFileViewer.java   Source Code and License 6 votes vote down vote up
@Override
public void zoomOut() {
	final ReferencedEnvelope env = pane.getDisplayArea();
	env.expandBy(env.getWidth() / 10, env.getHeight() / 10);
	pane.setDisplayArea(env);
}
 
Example 29
Project: gama   File: GamaOsmFile.java   Source Code and License 6 votes vote down vote up
public OSMInfo(final URL url, final long modificationStamp) {
	super(modificationStamp);
	CoordinateReferenceSystem crs = null;
	ReferencedEnvelope env2 = new ReferencedEnvelope();

	int number = 0;
	try {
		final File f = new File(url.toURI());
		final GamaOsmFile osmfile = new GamaOsmFile(null, f.getAbsolutePath());
		attributes.putAll(osmfile.getOSMAttributes(GAMA.getRuntimeScope()));

		final SimpleFeatureType TYPE = DataUtilities.createType("geometries", "geom:LineString");
		final ArrayList<SimpleFeature> list = new ArrayList<SimpleFeature>();
		for (final IShape shape : osmfile.iterable(null)) {
			list.add(SimpleFeatureBuilder.build(TYPE, new Object[] { shape.getInnerGeometry() }, null));
		}
		final SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, list);
		final SimpleFeatureSource featureSource = DataUtilities.source(collection);

		env2 = featureSource.getBounds();
		number = osmfile.nbObjects;
		crs = osmfile.getOwnCRS(null);
	} catch (final Exception e) {
		System.out.println("Error in reading metadata of " + url);
		hasFailed = true;

	} finally {

		// approximation of the width and height in meters.
		width = env2 != null ? env2.getWidth() * (FastMath.PI / 180) * 6378137 : 0;
		height = env2 != null ? env2.getHeight() * (FastMath.PI / 180) * 6378137 : 0;
		itemNumber = number;
		this.crs = crs;
	}

}
 
Example 30
Project: shapefile-geo   File: CellLocation.java   Source Code and License 6 votes vote down vote up
/**
 * An envelope representing the bounds of the current index
 * @return the Envelope
 */
public ReferencedEnvelope envelope() {
  Envelope worldEnvelope = reference.getEnvelope();
  double minX = worldEnvelope.getMinX();
  double minY = worldEnvelope.getMinY();
  double width = worldEnvelope.getWidth();
  double height = worldEnvelope.getHeight();
  int[] levelSizes = reference.getLevelSizes();
  int m = 1;
  for (int idx = 0; idx < locationIndices.length / 2; ++idx) {
    m *= levelSizes[idx];
    minX += (width / m) * locationIndices[idx * 2];
    minY += (height / m) * locationIndices[idx * 2 + 1];
  }
  double maxX = minX + (width / m);
  double maxY = minY + (height / m);
  return new ReferencedEnvelope(
    minX,
    maxX,
    minY,
    maxY,
    reference.getEnvelope().getCoordinateReferenceSystem()
  );
}
 
Example 31
Project: shapefile-geo   File: CellLocationReference.java   Source Code and License 6 votes vote down vote up
/**
 * Deserializes an attribute name into a CellLocationReference
 * @param envelope the bounding envelope (e.g. from a Shapefile bounds)
 * @param attributeName the name (e.g. from a Shapefile schema)
 * @return a CellLocationReference represented by the name
 * @see CellLocationReference#attributeName
 */
public static CellLocationReference fromAttributeName(ReferencedEnvelope envelope, String attributeName) {
  if (!attributeName.startsWith(AttributePrefix)) {
    throw new RuntimeException(attributeName + " does not start with expected prefix " + AttributePrefix);
  }

  String[] sizes = attributeName.substring(AttributePrefix.length()).split("_");
  if (sizes.length < 1) {
    throw new RuntimeException(attributeName + " has no sizes specified");
  }

  int[] levelSizes = new int[sizes.length];
  for (int idx = 0; idx < sizes.length; ++idx) {
    levelSizes[idx] = Integer.parseInt(sizes[idx]);
  }
  return new CellLocationReference(envelope, levelSizes);
}
 
Example 32
Project: elasticgeo   File: GeoHashGridProcessTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBasic() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    int width = 8;
    int height = 4;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 33
Project: elasticgeo   File: GeoHashGridProcessTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testScaled() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    int width = 16;
    int height = 8;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 34
Project: elasticgeo   File: GeoHashGridProcessTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSubCellCrop() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-168.75,168.75,-78.75,78.75,DefaultGeographicCRS.WGS84);
    int width = 16;
    int height = 8;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 35
Project: elasticgeo   File: GeoHashGridProcessTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSubCellCropWithSheer() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-168.75,168.75,-78.75,78.75,DefaultGeographicCRS.WGS84);
    int width = 900;
    int height = 600;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
}
 
Example 36
Project: elasticgeo   File: GeoHashGridTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGeoHashGrid() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    float[][] expected = new float[ny][nx];
    expected[ny-1][0] = 10;
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    IntStream.range(0, ny).forEach(i->assertTrue(Arrays.equals(expected[i], geohashGrid.getGrid()[i])));
}
 
Example 37
Project: elasticgeo   File: GeoHashGridTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGeoHashGrid_scaled() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",20))),
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(89.9,179.9),1),"doc_count",30)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.setScale(new RasterScale(5f, 10f));
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    float[][] expected = new float[ny][nx];
    expected[0][7] = 10;
    expected[ny-1][0] = 5;
    IntStream.range(0, ny).forEach(i->assertTrue(Arrays.equals(geohashGrid.getGrid()[i], expected[i])));
}
 
Example 38
Project: elasticgeo   File: GeohashUtilTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testComputePrecision() {
    assertEquals(1, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 32, 0.9));
    assertEquals(2, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 1024, 0.9));
    assertEquals(3, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 32768, 0.9));

    assertEquals(2, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 1000, 0.9));
    assertEquals(3, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 1500, 0.9));

    assertEquals(1, GeohashUtil.computePrecision(new ReferencedEnvelope(EVERYTHING.getMinX(),EVERYTHING.getMaxX(),EVERYTHING.getMinY(),EVERYTHING.getMaxY(),null), 32, 0.9));

    assertEquals(1, GeohashUtil.computePrecision(new ReferencedEnvelope(-1,1,-1,1,null), 0, 0.9));
    assertEquals(6, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), (long) 1e9, 0.9));
    assertEquals(6, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 1, 1e9));
    assertEquals(1, GeohashUtil.computePrecision(new ReferencedEnvelope(-180,180,-90,90,null), 1, -1e9));
}
 
Example 39
Project: platypus-js   File: JGeoPane.java   Source Code and License 6 votes vote down vote up
@Override
protected void paintScreenContext(Graphics2D g) {
    if (screenContext != null) {
        synchronized (screenContext) {
            try {
                // let's paint selection and phanton layers
                screenRenderer.setMapContent(screenContext);
                Rectangle clip = g.getClipBounds();
                Point2D.Double lu = screen2Cartesian(clip.getLocation());
                Point2D.Double br = screen2Cartesian(new Point(clip.x + clip.width, clip.y + clip.height));
                Geometry aoiGeometry = constructRectyPolygonGeometry(lu, br);
                Envelope aoiEnvelope = new ReferencedEnvelope(aoiGeometry.getEnvelopeInternal(), screenContext.getCoordinateReferenceSystem());
                screenRenderer.paint(g, clip, aoiEnvelope, cartesian2Screen);
            } catch (NoninvertibleTransformException ex) {
                Logger.getLogger(JGeoPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    super.paintScreenContext(g);
}
 
Example 40
Project: s2tbx   File: S2tbxMosaicOp.java   Source Code and License 6 votes vote down vote up
/**
 * STEP 3 methods
 */

private ReferencedEnvelope computeMosaicBounds() {
    final Rectangle2D initialBounds = new Rectangle2D.Double();
    initialBounds.setFrameFromDiagonal(this.westBound, this.southBound, this.eastBound, this.northBound);
    final ReferencedEnvelope boundsEnvelope = new ReferencedEnvelope(initialBounds, DefaultGeographicCRS.WGS84);
    try {
        return boundsEnvelope.transform(this.targetCRS, true);
    } catch (TransformException | FactoryException e) {
        throw new OperatorException(e);
    }
}