Search in sources :

Example 16 with Envelope

use of org.opengis.geometry.Envelope in project polymap4-core by Polymap4.

the class WmsRenderProcessor method setBBox.

protected void setBBox(org.geotools.data.wms.request.GetMapRequest getMap, Envelope envelope) {
    // code is from AbstractGetMapRequest
    String version = getMap.getProperties().getProperty(Request.VERSION);
    boolean forceXY = version == null || !version.startsWith("1.3");
    String srsName = CRS.toSRS(envelope.getCoordinateReferenceSystem());
    CoordinateReferenceSystem crs = AbstractGetMapRequest.toServerCRS(srsName, forceXY);
    Envelope bbox = null;
    try {
        bbox = CRS.transform(envelope, crs);
    } catch (TransformException e) {
        bbox = envelope;
    }
    // FIXME
    String s = srsName.contains("31468") && version.startsWith("1.3") ? Joiner.on(',').join(bbox.getMinimum(1), bbox.getMinimum(0), bbox.getMaximum(1), bbox.getMaximum(0)) : Joiner.on(',').join(bbox.getMinimum(0), bbox.getMinimum(1), bbox.getMaximum(0), bbox.getMaximum(1));
    // log.info( "Requested BBOX: " + s );
    getMap.setBBox(s);
}
Also used : TransformException(org.opengis.referencing.operation.TransformException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.opengis.geometry.Envelope) CRSEnvelope(org.geotools.data.ows.CRSEnvelope)

Example 17 with Envelope

use of org.opengis.geometry.Envelope in project sldeditor by robward-scisys.

the class ReferencedEnvlopeValuesTest method testReferencedEnvelopeValues.

/**
 * Test method for {@link
 * com.sldeditor.rendertransformation.types.ReferencedEnvelopeValues#ReferencedEnvelopeValues()}.
 */
@Test
void testReferencedEnvelopeValues() {
    ReferencedEnvelopeValues testObj = new ReferencedEnvelopeValues();
    testObj.createInstance();
    assertEquals(Arrays.asList(ReferencedEnvelope.class, Envelope.class, BoundingBox.class), testObj.getType());
    CoordinateReferenceSystem crs = null;
    ReferencedEnvelope envelope = new ReferencedEnvelope(-1.0, 1.0, -1.0, 1.0, crs);
    testObj.setDefaultValue(envelope);
    assertNull(testObj.getExpression());
    // ReferencedEnvelope value
    testObj.setValue((Envelope) crs);
    assertNull(testObj.getExpression());
    // Literal expression
    Expression expectedExpression = ff.literal(crs);
    testObj.setValue(expectedExpression);
    assertEquals(expectedExpression, testObj.getExpression());
    // Attribute expression
    expectedExpression = ff.property("test");
    testObj.setValue(expectedExpression);
    assertEquals(expectedExpression, testObj.getExpression());
    // Not set
    testObj.setValue("");
    assertNull(testObj.getExpression());
    FieldConfigBase field = testObj.getField(new FieldConfigCommonData(ReferencedEnvelopeValues.class, FieldIdEnum.INITIAL_GAP, "label", true, false, false));
    assertEquals(FieldConfigBoundingBox.class, field.getClass());
    // Increase code coverage
    TestReferencedEnvelopeValues testObj2 = new TestReferencedEnvelopeValues();
    testObj2.populateSymbolType(null);
}
Also used : ReferencedEnvelopeValues(com.sldeditor.rendertransformation.types.ReferencedEnvelopeValues) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) FieldConfigBase(com.sldeditor.ui.detail.config.FieldConfigBase) Expression(org.opengis.filter.expression.Expression) FieldConfigBoundingBox(com.sldeditor.ui.detail.config.FieldConfigBoundingBox) BoundingBox(org.opengis.geometry.BoundingBox) FieldConfigCommonData(com.sldeditor.ui.detail.config.FieldConfigCommonData) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.opengis.geometry.Envelope) Test(org.junit.jupiter.api.Test)

Example 18 with Envelope

use of org.opengis.geometry.Envelope in project sis by apache.

the class FeatureTypeBuilderTest method testEnvelopeOverride.

/**
 * Tests overriding the "sis:envelope" property. This may happen when the user wants to specify
 * envelope himself instead than relying on the automatically computed value.
 */
@Test
public void testEnvelopeOverride() {
    FeatureTypeBuilder builder = new FeatureTypeBuilder().setName("CoverageRecord").setAbstract(true);
    builder.addAttribute(Geometry.class).setName(AttributeConvention.GEOMETRY_PROPERTY).addRole(AttributeRole.DEFAULT_GEOMETRY);
    final DefaultFeatureType parentType = builder.build();
    builder = new FeatureTypeBuilder().setName("Record").setSuperTypes(parentType);
    builder.addAttribute(Envelope.class).setName(AttributeConvention.ENVELOPE_PROPERTY);
    final DefaultFeatureType childType = builder.build();
    final Iterator<? extends AbstractIdentifiedType> it = childType.getProperties(true).iterator();
    assertPropertyEquals("sis:envelope", Envelope.class, it.next());
    assertPropertyEquals("sis:geometry", Geometry.class, it.next());
    assertFalse(it.hasNext());
}
Also used : DefaultFeatureType(org.apache.sis.feature.DefaultFeatureType) Envelope(org.opengis.geometry.Envelope) DefaultFeatureTypeTest(org.apache.sis.feature.DefaultFeatureTypeTest) Test(org.junit.Test)

Example 19 with Envelope

use of org.opengis.geometry.Envelope in project sis by apache.

the class LocationFormat method format.

/**
 * Writes a textual representation of the given location in the given stream or buffer.
 *
 * <div class="warning"><b>Upcoming API change — generalization</b><br>
 * in a future SIS version, the type of {@code location} parameter may be generalized
 * to the {@code org.opengis.referencing.gazetteer.Location} interface.
 * This change is pending GeoAPI revision.</div>
 *
 * @param  location    the location to format.
 * @param  toAppendTo  where to format the location.
 * @throws IOException if an error occurred while writing to the given appendable.
 */
@Override
@SuppressWarnings({ "fallthrough", "null" })
public void format(final AbstractLocation location, final Appendable toAppendTo) throws IOException {
    ArgumentChecks.ensureNonNull("location", location);
    final Locale locale = getLocale(Locale.Category.DISPLAY);
    final Vocabulary vocabulary = Vocabulary.getResources(locale);
    final TableAppender table = new TableAppender(toAppendTo, "│ ", columnSeparator, " │");
    table.setMultiLinesCells(true);
    /*
         * Location type.
         */
    table.appendHorizontalSeparator();
    final AbstractLocationType type = location.type();
    if (type != null) {
        append(table, vocabulary, Vocabulary.Keys.LocationType, toString(type.getName(), locale));
    }
    /*
         * Geographic identifier and alternative identifiers, if any.
         */
    append(table, vocabulary, Vocabulary.Keys.GeographicIdentifier, toString(location.getGeographicIdentifier(), locale));
    final Collection<? extends InternationalString> alt = location.getAlternativeGeographicIdentifiers();
    if (alt != null && !alt.isEmpty()) {
        boolean isFirst = true;
        vocabulary.appendLabel(Vocabulary.Keys.AlternativeIdentifiers, table);
        nextColumn(table);
        for (final InternationalString id : alt) {
            if (!isFirst) {
                isFirst = false;
                table.append(lineSeparator);
            }
            table.append(id);
        }
        table.nextLine();
    }
    /*
         * Extents (temporal and geographic). If an envelope exists and the CRS is not geographic,
         * then the envelope bounds will be appended on the same lines than the geographic bounds.
         * But before writing the bounding box and/or the envelope, check if they are redundant.
         * We may also need to change axis order (but not unit) of the envelope in order to match
         * the axis order of the geographic bounding box.
         */
    final Extent extent = new DefaultExtent(null, location.getGeographicExtent(), null, location.getTemporalExtent());
    final Range<Date> time = Extents.getTimeRange(extent);
    if (time != null) {
        append(table, vocabulary, Vocabulary.Keys.StartDate, toString(time.getMinValue()));
        append(table, vocabulary, Vocabulary.Keys.EndDate, toString(time.getMaxValue()));
    }
    GeographicBoundingBox bbox = Extents.getGeographicBoundingBox(extent);
    Envelope envelope = location.getEnvelope();
    DirectPosition position = position(location.getPosition());
    // Position in geographic CRS.
    DirectPosition geopos = null;
    // Envelope Coordinate Reference System.
    CoordinateReferenceSystem crs = null;
    // CRS in conventional (x,y) axis order.
    CoordinateReferenceSystem normCRS = null;
    // If failed to transform envelope.
    Exception warning = null;
    try {
        if (envelope != null) {
            normCRS = normalize(crs = envelope.getCoordinateReferenceSystem());
            if (normCRS != crs) {
                // Should only change order and sign.
                envelope = Envelopes.transform(envelope, normCRS);
            }
        }
        if (position != null) {
            /*
                 * If only one of the envelope or the position objects specify a CRS, assume that the other object
                 * use the same CRS. If both the envelope and the position objects specify a CRS, the envelope CRS
                 * will have precedence and the "representative position" will be projected to that CRS.
                 */
            final CoordinateReferenceSystem posCRS = position.getCoordinateReferenceSystem();
            if (normCRS == null) {
                normCRS = normalize(crs = posCRS);
                if (normCRS != crs) {
                    // Should only change order and sign.
                    envelope = Envelopes.transform(envelope, normCRS);
                }
            }
            if (bbox != null) {
                // Compute geographic position only if there is a geographic bounding box.
                GeographicCRS geogCRS = ReferencingUtilities.toNormalizedGeographicCRS(posCRS);
                if (geogCRS != null) {
                    geopos = transform(position, posCRS, geogCRS);
                }
            }
            position = transform(position, posCRS, normCRS);
        }
    } catch (FactoryException | TransformException e) {
        envelope = null;
        position = null;
        warning = e;
    }
    /*
         * At this point we got the final geographic bounding box and/or envelope to write.
         * Since we will write the projected and geographic coordinates side-by-side in the same cells,
         * we need to format them in advance so we can compute their width for internal right-alignment.
         * We do the alignment ourselves instead than using TableAppender.setCellAlignment(ALIGN_RIGHT)
         * because we do not want (projected geographic) tuple to appear far on the right side if other
         * cells have long texts.
         */
    if (bbox != null || envelope != null) {
        final CoordinateSystem cs = (crs != null) ? crs.getCoordinateSystem() : null;
        String[] geographic = null;
        String[] projected = null;
        String[] unitSymbol = null;
        AngleFormat geogFormat = null;
        NumberFormat projFormat = null;
        UnitFormat unitFormat = null;
        int maxGeogLength = 0;
        int maxProjLength = 0;
        int maxUnitLength = 0;
        boolean showProj = false;
        if (bbox != null || geopos != null) {
            geogFormat = (AngleFormat) getFormat(Angle.class);
            geographic = new String[BOUND_KEY.length];
            Arrays.fill(geographic, "");
        }
        if (envelope != null || position != null) {
            projFormat = (NumberFormat) getFormat(Number.class);
            unitFormat = (UnitFormat) getFormat(Unit.class);
            projected = new String[BOUND_KEY.length];
            unitSymbol = new String[BOUND_KEY.length];
            Arrays.fill(projected, "");
            Arrays.fill(unitSymbol, "");
        }
        for (int i = 0; i < BOUND_KEY.length; i++) {
            RoundingMode rounding = RoundingMode.FLOOR;
            double g = Double.NaN;
            double p = Double.NaN;
            int dimension = 0;
            switch(i) {
                case 0:
                    if (bbox != null)
                        g = bbox.getWestBoundLongitude();
                    if (envelope != null)
                        p = envelope.getMinimum(0);
                    break;
                case 2:
                    if (bbox != null)
                        g = bbox.getEastBoundLongitude();
                    if (envelope != null)
                        p = envelope.getMaximum(0);
                    rounding = RoundingMode.CEILING;
                    break;
                case 3:
                    if (bbox != null)
                        g = bbox.getSouthBoundLatitude();
                    if (envelope != null)
                        p = envelope.getMinimum(1);
                    dimension = 1;
                    break;
                case 5:
                    if (bbox != null)
                        g = bbox.getNorthBoundLatitude();
                    if (envelope != null)
                        p = envelope.getMaximum(1);
                    rounding = RoundingMode.CEILING;
                    dimension = 1;
                    break;
                // Fall through
                case 4:
                    dimension = 1;
                case 1:
                    if (geopos != null)
                        g = geopos.getOrdinate(dimension);
                    if (position != null)
                        p = position.getOrdinate(dimension);
                    rounding = RoundingMode.HALF_EVEN;
                    break;
            }
            if (!Double.isNaN(p)) {
                showProj |= (g != p);
                if (cs != null) {
                    final Unit<?> unit = cs.getAxis(dimension).getUnit();
                    if (unit != null) {
                        final int length = (unitSymbol[i] = unitFormat.format(unit)).length();
                        if (length > maxUnitLength) {
                            maxUnitLength = length;
                        }
                    }
                }
                try {
                    projFormat.setRoundingMode(rounding);
                } catch (UnsupportedOperationException e) {
                // Ignore.
                }
                final int length = (projected[i] = projFormat.format(p)).length();
                if (length > maxProjLength) {
                    maxProjLength = length;
                }
            }
            if (!Double.isNaN(g)) {
                geogFormat.setRoundingMode(rounding);
                final Angle angle = (dimension == 0) ? new Longitude(g) : new Latitude(g);
                final int length = (geographic[i] = geogFormat.format(angle)).length();
                if (length > maxGeogLength) {
                    maxGeogLength = length;
                }
            }
        }
        if (!showProj) {
            // All projected coordinates are identical to geographic ones.
            projected = null;
            unitSymbol = null;
            maxProjLength = 0;
            maxUnitLength = 0;
        } else if (maxProjLength != 0) {
            if (maxUnitLength != 0) {
                maxUnitLength++;
            }
            // Arbitrary space between projected and geographic coordinates.
            maxGeogLength += 4;
        }
        /*
             * At this point all coordinates have been formatted in advance.
             */
        final String separator = (projected != null && geographic != null) ? "    —" : "";
        for (int i = 0; i < BOUND_KEY.length; i++) {
            final String p = (projected != null) ? projected[i] : "";
            final String u = (unitSymbol != null) ? unitSymbol[i] : "";
            final String g = (geographic != null) ? geographic[i] : "";
            if (!p.isEmpty() || !g.isEmpty()) {
                vocabulary.appendLabel(BOUND_KEY[i], table);
                nextColumn(table);
                table.append(CharSequences.spaces(maxProjLength - p.length())).append(p);
                table.append(CharSequences.spaces(maxUnitLength - u.length())).append(u).append(separator);
                table.append(CharSequences.spaces(maxGeogLength - g.length())).append(g);
                table.nextLine();
            }
        }
    }
    if (crs != null) {
        append(table, vocabulary, Vocabulary.Keys.CoordinateRefSys, IdentifiedObjects.getName(crs, null));
    }
    /*
         * Organization responsible for defining the characteristics of the location instance.
         */
    final AbstractParty administrator = location.getAdministrator();
    if (administrator != null) {
        append(table, vocabulary, Vocabulary.Keys.Administrator, toString(administrator.getName(), locale));
    }
    table.appendHorizontalSeparator();
    table.flush();
    if (warning != null) {
        vocabulary.appendLabel(Vocabulary.Keys.Warnings, toAppendTo);
        toAppendTo.append(warning.toString()).append(lineSeparator);
    }
}
Also used : Locale(java.util.Locale) Vocabulary(org.apache.sis.util.resources.Vocabulary) DirectPosition(org.opengis.geometry.DirectPosition) DefaultExtent(org.apache.sis.metadata.iso.extent.DefaultExtent) Extent(org.opengis.metadata.extent.Extent) FactoryException(org.opengis.util.FactoryException) CoordinateSystem(org.opengis.referencing.cs.CoordinateSystem) UnitFormat(org.apache.sis.measure.UnitFormat) RoundingMode(java.math.RoundingMode) TableAppender(org.apache.sis.io.TableAppender) Latitude(org.apache.sis.measure.Latitude) GeographicBoundingBox(org.opengis.metadata.extent.GeographicBoundingBox) InternationalString(org.opengis.util.InternationalString) AngleFormat(org.apache.sis.measure.AngleFormat) Envelope(org.opengis.geometry.Envelope) DefaultExtent(org.apache.sis.metadata.iso.extent.DefaultExtent) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) GeographicCRS(org.opengis.referencing.crs.GeographicCRS) AbstractParty(org.apache.sis.metadata.iso.citation.AbstractParty) TransformException(org.opengis.referencing.operation.TransformException) Longitude(org.apache.sis.measure.Longitude) Date(java.util.Date) ParseException(java.text.ParseException) TransformException(org.opengis.referencing.operation.TransformException) IOException(java.io.IOException) FactoryException(org.opengis.util.FactoryException) Angle(org.apache.sis.measure.Angle) InternationalString(org.opengis.util.InternationalString) NumberFormat(java.text.NumberFormat)

Example 20 with Envelope

use of org.opengis.geometry.Envelope in project sis by apache.

the class NADCONTest method writeSubGrid.

// ////////////////////////////////////////////////
// //////                                  ////////
// //////        TEST FILE CREATION        ////////
// //////                                  ////////
// ////////////////////////////////////////////////
/**
 * Writes a sub-grid of the given grid in pseudo-NADCON ASCII format.
 * This method is used only for creating the test file, and the output is not fully NADCON compliant.
 * We take this opportunity for testing the parser capability to be lenient.
 *
 * <p>This method has been executed once for creating the {@code "conus-extract.laa"} and
 * {@code "conus-extract.loa"} test files and should not be needed anymore, but we keep it
 * around in case we have new test files to generate. The parameter used for creating the
 * test file are:</p>
 *
 * <ul>
 *   <li>{@code gridX} = 125</li>
 *   <li>{@code gridY} =  70</li>
 *   <li>{@code nx}    =   8</li>
 *   <li>{@code ny}    =  10</li>
 * </ul>
 *
 * This ensure that the grid indices (129.83277, 76.89632) is included in the test file.
 * Those grid indices is the location of the (39°13′26.71″N, 98°32′31.75″W) test point to interpolate.
 *
 * @param  grid   the full grid from which to extract a few values.
 * @param  file   where to write the test file.
 * @param  dim    0 for writing longitudes, or 1 for writing latitudes.
 * @param  gridX  index along the longitude axis of the first cell to write.
 * @param  gridY  index along the latitude axis of the first cell to write.
 * @param  nx     number of cells to write along the longitude axis.
 * @param  ny     number of cells to write along the latitude axis.
 * @throws TransformException if an error occurred while computing the envelope.
 * @throws IOException if an error occurred while writing the test file.
 */
public static void writeSubGrid(final DatumShiftGridFile<Angle, Angle> grid, final Path file, final int dim, final int gridX, final int gridY, final int nx, final int ny) throws IOException, TransformException {
    Envelope envelope = new Envelope2D(null, gridX, gridY, nx - 1, ny - 1);
    envelope = Envelopes.transform(grid.getCoordinateToGrid().inverse(), envelope);
    try (BufferedWriter out = Files.newBufferedWriter(file)) {
        out.write("NADCON EXTRACTED REGION\n");
        out.write(String.format(Locale.US, "%4d %3d %3d %11.5f %11.5f %11.5f %11.5f %11.5f\n", nx, ny, 1, envelope.getMinimum(0), envelope.getSpan(0) / (nx - 1), envelope.getMinimum(1), envelope.getSpan(1) / (ny - 1), 0.0));
        for (int y = 0; y < ny; y++) {
            for (int x = 0; x < nx; x++) {
                out.write(String.format(Locale.US, " %11.6f", grid.getCellValue(dim, gridX + x, gridY + y)));
            }
            out.write('\n');
        }
    }
}
Also used : Envelope(org.opengis.geometry.Envelope) Envelope2D(org.apache.sis.geometry.Envelope2D) BufferedWriter(java.io.BufferedWriter)

Aggregations

Envelope (org.opengis.geometry.Envelope)25 Test (org.junit.Test)11 Rectangle2D (java.awt.geom.Rectangle2D)7 Envelope2D (org.apache.sis.geometry.Envelope2D)5 DirectPosition (org.opengis.geometry.DirectPosition)5 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)5 GeneralEnvelope (org.apache.sis.geometry.GeneralEnvelope)4 TransformException (org.opengis.referencing.operation.TransformException)4 GeographicBoundingBox (org.opengis.metadata.extent.GeographicBoundingBox)3 Angle (javax.measure.quantity.Angle)2 Matrix3 (org.apache.sis.referencing.operation.matrix.Matrix3)2 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)2 GeographicCRS (org.opengis.referencing.crs.GeographicCRS)2 CoordinateSystem (org.opengis.referencing.cs.CoordinateSystem)2 ReferencedEnvelopeValues (com.sldeditor.rendertransformation.types.ReferencedEnvelopeValues)1 FieldConfigBase (com.sldeditor.ui.detail.config.FieldConfigBase)1 FieldConfigBoundingBox (com.sldeditor.ui.detail.config.FieldConfigBoundingBox)1 FieldConfigCommonData (com.sldeditor.ui.detail.config.FieldConfigCommonData)1 Shape (java.awt.Shape)1 BufferedWriter (java.io.BufferedWriter)1