Java org.geotools.geometry.jts.JTS 代码实例

・21 分钟阅读

以下是展示如何使用org.geotools.geometry.jts.JTS的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


private Query makeDatastoreQuery(String _bbox, SimpleFeatureSource results,
                                 int finalMaxFeatures, String[] attributes, CoordinateReferenceSystem crs, CoordinateReferenceSystem targetCrs) throws FactoryException, TransformException {
    GeometryFactory fac = new GeometryFactory();
    Geometry referenceGeom;
    String[] bbox = _bbox.split(",");
    double minx = parseDouble(bbox[0]);
    double miny = parseDouble(bbox[1]);
    double maxx = parseDouble(bbox[2]);
    double maxy = parseDouble(bbox[3]);
    Envelope env = new Envelope(minx, maxx, miny, maxy);
    referenceGeom = fac.toGeometry(env);
    final CoordinateReferenceSystem nativeCrs = results.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem();
    if (nativeCrs != null) {
        JTS.transform(referenceGeom, CRS.findMathTransform(crs, nativeCrs, true));
    }
    final SimpleFeatureType schema = results.getSchema();
    String geometryAttributeName = schema.getGeometryDescriptor().getLocalName();
    FilterFactory2 filterFactory2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
    final PropertyName geomAttribute = filterFactory2.property(geometryAttributeName);
    Intersects filter = filterFactory2.intersects(geomAttribute, filterFactory2.literal(referenceGeom));
    if (attributes != null) {
        for (int i = 0; i < attributes.length; i++) {
            attributes[i] = attributes[i].trim();
        }
    }
    final Query query = new Query(schema.getTypeName(), filter, attributes);
    query.setCoordinateSystemReproject(targetCrs);
    query.setMaxFeatures(finalMaxFeatures);
    return query;
}
 

实例 2


private Query makeDatastoreQuery(String _bbox, SimpleFeatureSource results,
                                 int finalMaxFeatures, String[] attributes, CoordinateReferenceSystem crs, CoordinateReferenceSystem targetCrs) throws FactoryException, TransformException {
    GeometryFactory fac = new GeometryFactory();
    Geometry referenceGeom;
    String[] bbox = _bbox.split(",");
    double minx = parseDouble(bbox[0]);
    double miny = parseDouble(bbox[1]);
    double maxx = parseDouble(bbox[2]);
    double maxy = parseDouble(bbox[3]);
    Envelope env = new Envelope(minx, maxx, miny, maxy);
    referenceGeom = fac.toGeometry(env);
    final CoordinateReferenceSystem nativeCrs = results.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem();
    if (nativeCrs != null) {
        JTS.transform(referenceGeom, CRS.findMathTransform(crs, nativeCrs, true));
    }
    final SimpleFeatureType schema = results.getSchema();
    String geometryAttributeName = schema.getGeometryDescriptor().getLocalName();
    FilterFactory2 filterFactory2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
    final PropertyName geomAttribute = filterFactory2.property(geometryAttributeName);
    Intersects filter = filterFactory2.intersects(geomAttribute, filterFactory2.literal(referenceGeom));
    if (attributes != null) {
        for (int i = 0; i < attributes.length; i++) {
            attributes[i] = attributes[i].trim();
        }
    }
    final Query query = new Query(schema.getTypeName(), filter, attributes);
    query.setCoordinateSystemReproject(targetCrs);
    query.setMaxFeatures(finalMaxFeatures);
    return query;
}
 

实例 3


/**
 * Transforms a geometry from the shape file to a geometry with WGS84 projection.
 * @param geometry a geometry from the shape file
 * @return a geometry with WGS84 projection
 * @throws MismatchedDimensionException if the transformation fails
 * @throws TransformException if the geometry could not be transformed
 */
private Geometry transformToWGS84(Geometry geometry)
                throws MismatchedDimensionException, TransformException {
        if (transformation == null) {
                return geometry;
        } else {
                return JTS.transform(geometry, transformation);
        }
}
 

实例 4


private void setEnv(@Nullable Bounded bounded, ReferencedEnvelope env,
        Optional<ObjectId> metadataId) {
    env.setToNull();
    if (bounded == null) {
        return;
    }
    bounded.expand(env);
    if (env.isNull()) {
        return;
    }
    ObjectId mdid;
    if (metadataId.isPresent()) {
        mdid = metadataId.get();
        MathTransform transform = getMathTransform(mdid);
        if (transform.isIdentity()) {
            return;
        }
        Envelope targetEnvelope = new ReferencedEnvelope(crs);
        try {
            int densifyPoints = isPoint(env) ? 1 : 5;
            JTS.transform(env, targetEnvelope, transform, densifyPoints);
            env.init(targetEnvelope);
        } catch (TransformException e) {
            throw Throwables.propagate(e);
        }
    }
}
 

实例 5


public static Envelope reprojectEnvelopeByEpsg( int srcEpsg, int destEpsg, Envelope srcEnvelope ) throws FactoryException,
        TransformException {
    CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:" + srcEpsg); //$NON-NLS-1$
    CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + destEpsg); //$NON-NLS-1$
    MathTransform tr = CRS.findMathTransform(sourceCRS, targetCRS);
    // From that point, I'm not sure which kind of object is returned by
    // getLatLonBoundingBox(). But there is some convenience methods if CRS
    // like:
    return JTS.transform(srcEnvelope, tr);
}
 

实例 6


/**
 * Reprojects a {@link JGrassRegion region}.
 * 
 * @param sourceCRS
 *            the original {@link CoordinateReferenceSystem crs} of the
 *            region.
 * @param targetCRS
 *            the target {@link CoordinateReferenceSystem crs} of the
 *            region.
 * @param lenient
 *            defines whether to apply a lenient transformation or not.
 * @return a new {@link JGrassRegion region}.
 * @throws Exception
 *             exception that may be thrown when applying the
 *             transformation.
 */
public JGrassRegion reproject( CoordinateReferenceSystem sourceCRS,
        CoordinateReferenceSystem targetCRS, boolean lenient ) throws Exception {
    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient);
    Envelope envelope = getEnvelope();
    Envelope targetEnvelope = JTS.transform(envelope, transform);
    return new JGrassRegion(targetEnvelope.getMinX(), targetEnvelope.getMaxX(), targetEnvelope
            .getMinY(), targetEnvelope.getMaxY(), getRows(), getCols());
}
 

实例 7


@Test
public void testGetBoundsQuery() throws Exception {
    ReferencedEnvelope bounds;
    Filter filter;
    filter = ff.id(Collections.singleton(ff.featureId(RepositoryTestCase.idP2)));
    bounds = pointsSource.getBounds(new Query(pointsName, filter));
    assertEquals(boundsOf(points2), bounds);
    ReferencedEnvelope queryBounds = boundsOf(points1, points2);
    Polygon geometry = JTS.toGeometry(queryBounds);
    filter = ff.intersects(ff.property(pointsType.getGeometryDescriptor().getLocalName()),
            ff.literal(geometry));
    bounds = pointsSource.getBounds(new Query(pointsName, filter));
    assertEquals(boundsOf(points1, points2), bounds);
    ReferencedEnvelope transformedQueryBounds;
    CoordinateReferenceSystem queryCrs = CRS.decode("EPSG:3857");
    transformedQueryBounds = queryBounds.transform(queryCrs, true);
    geometry = JTS.toGeometry(transformedQueryBounds);
    geometry.setUserData(queryCrs);
    filter = ff.intersects(ff.property(pointsType.getGeometryDescriptor().getLocalName()),
            ff.literal(geometry));
    bounds = pointsSource.getBounds(new Query(pointsName, filter));
    assertEquals(boundsOf(points1, points2), bounds);
    filter = ECQL.toFilter("sp = 'StringProp2_3' OR ip = 2000");
    bounds = linesSource.getBounds(new Query(linesName, filter));
    assertEquals(boundsOf(lines3, lines2), bounds);
}
 

实例 8


@Test
public void testGetCount() throws Exception {
    assertEquals(3, pointsSource.getCount(Query.ALL));
    assertEquals(3, linesSource.getCount(Query.ALL));
    Filter filter;
    filter = ff.id(Collections.singleton(ff.featureId(RepositoryTestCase.idP2)));
    assertEquals(1, pointsSource.getCount(new Query(pointsName, filter)));
    ReferencedEnvelope queryBounds = boundsOf(points1, points2);
    Polygon geometry = JTS.toGeometry(queryBounds);
    filter = ff.intersects(ff.property(pointsType.getGeometryDescriptor().getLocalName()),
            ff.literal(geometry));
    assertEquals(2, pointsSource.getCount(new Query(pointsName, filter)));
    ReferencedEnvelope transformedQueryBounds;
    CoordinateReferenceSystem queryCrs = CRS.decode("EPSG:3857");
    transformedQueryBounds = queryBounds.transform(queryCrs, true);
    geometry = JTS.toGeometry(transformedQueryBounds);
    geometry.setUserData(queryCrs);
    filter = ff.intersects(ff.property(pointsType.getGeometryDescriptor().getLocalName()),
            ff.literal(geometry));
    assertEquals(2, pointsSource.getCount(new Query(pointsName, filter)));
    filter = ECQL.toFilter("sp = 'StringProp2_3' OR ip = 2000");
    assertEquals(2, linesSource.getCount(new Query(linesName, filter)));
}
 

实例 9


private Literal clipToWorld(Literal geometry) {
    if(geometry != null) {
        Geometry g = geometry.evaluate(null, Geometry.class);
        if(g != null) {
            Envelope env = g.getEnvelopeInternal();
            // first, limit to world
            if(!WORLD.contains(env)) {
                g = sanitizePolygons(g.intersection(JTS.toGeometry(WORLD)));
            }
            // second, postgis will always use the shortest distance between two
            // points, if an arc is longer than 180 degrees the opposite will
            // be used instead, so we have to slice the geometry in parts
            env = g.getEnvelopeInternal();
            if(Math.sqrt(env.getWidth() * env.getWidth() + env.getHeight() * env.getHeight()) >= 180) {
                // slice in 90x90 degrees quadrants, none of them has a diagonal longer than 180
                final List<Polygon> polygons = new ArrayList<Polygon>();
                for(double lon = Math.floor(env.getMinX()); lon < env.getMaxX(); lon+= 90) {
                    for (double lat = Math.floor(env.getMinY()); lat < env.getMaxY(); lat += 90) {
                        Geometry quadrant = JTS.toGeometry(new Envelope(lon, lon + 90, lat, lat + 90));
                        Geometry cut = sanitizePolygons(g.intersection(quadrant));
                        if(!cut.isEmpty()) {
                            if(cut instanceof Polygon) {
                                polygons.add((Polygon) cut);
                            } else {
                                for (int i = 0; i < cut.getNumGeometries(); i++) {
                                    polygons.add((Polygon) cut.getGeometryN(i));
                                }
                            }
                        }
                    }
                }
                g = toPolygon(g.getFactory(), polygons);
            }
            geometry = CommonFactoryFinder.getFilterFactory(null).literal(g);
        }
    }
    return geometry;
}
 

实例 10


/**
 * Returns true if the geometry covers the entire world
 * @param geometry
 * @return
 */
private boolean isWorld(Literal geometry) {
    if(geometry != null) {
        Geometry g = geometry.evaluate(null, Geometry.class);
        if(g != null) {
            return JTS.toGeometry(WORLD).equalsTopo(g.union());
        }
    }
    return false;
}
 

实例 11


private Geometry parseLookAtBBOX(Object object) {
    Geometry bbox = null;
    if (null != object) {
        Envelope env;
        try {
            BBoxKvpParser parser = new BBoxKvpParser();
            env = (Envelope) parser.parse(String.valueOf(object));
            bbox = JTS.toGeometry(env);
        } catch (Exception e) {
            LOGGER.log(Level.FINER, e.getMessage(), e);
        }
    }
    return bbox;
}
 

实例 12


protected void addBbox(Set<Attribute> resources) {
    org.geoserver.ows.Request owsRequest = Dispatcher.REQUEST.get();
    if (owsRequest == null)
        return;
    Map kvp = owsRequest.getKvp();
    if (kvp == null)
        return;
    ReferencedEnvelope env = (ReferencedEnvelope) kvp.get("BBOX");
    if (env == null)
        return;
    String srsName = (String) kvp.get("SRS");
    Geometry geom = JTS.toGeometry((Envelope) env);
    addGeometry(resources, XACMLConstants.BBoxResourceURI, geom, srsName);
}
 

实例 13


/**
 * Returns the tile range of the mask bounding box at a specific zoom level.
 * 
 * @param i
 * @return the bounds of the set tiles for the given level, or {@code null} if none is set
 */
public synchronized long[] getCoveredBounds(final int level) {
    if (aggregatedGeomBounds == null) {
        return null;
    }
    /*
     * Get the best fit for the level
     */
    final long[] coverage = getGridCoverage(level);
    final BoundingBox coverageBounds = gridSubset.boundsFromRectangle(coverage);
    final MathTransform worldToGrid = getWorldToGridTransform(coverageBounds, coverage);
    BoundingBox expandedBounds;
    try {
        Envelope coveredLevelEnvelope;
        coveredLevelEnvelope = JTS.transform(aggregatedGeomBounds, worldToGrid);
        Geometry bufferedEnvelopeInGridCrs;
        bufferedEnvelopeInGridCrs = JTS.toGeometry(coveredLevelEnvelope).buffer(
                ENVELOPE_BUFFER_RATIO);
        coveredLevelEnvelope = bufferedEnvelopeInGridCrs.getEnvelopeInternal();
        MathTransform gridToWorld = worldToGrid.inverse();
        Envelope bufferedEnvelope = JTS.transform(coveredLevelEnvelope, gridToWorld);
        expandedBounds = new BoundingBox(bufferedEnvelope.getMinX(),
                bufferedEnvelope.getMinY(), bufferedEnvelope.getMaxX(),
                bufferedEnvelope.getMaxY());
    } catch (TransformException e) {
        throw new RuntimeException(e);
    }
    long[] coveredBounds = gridSubset.getCoverageIntersection(level, expandedBounds);
    return coveredBounds;
}
 

实例 14


public static String convertToMultiPolygonWKT( Collection<Position> polygons ) {
    GeometryFactory geometryFactory = new GeometryFactory();
    com.vividsolutions.jts.geom.Polygon[] polygonArray = new com.vividsolutions.jts.geom.Polygon[polygons.size()];
    Iterator<Position> polygonIterator = polygons.iterator();
    for ( int i = 0; i < polygons.size(); i++ ) {
        Position position = polygonIterator.next();
        if ( position instanceof Box ) {
            Box box = (Box) position;
            com.vividsolutions.jts.geom.Coordinate coord1 = convertCoordinateToJTS( box.getLowerCorner() );
            com.vividsolutions.jts.geom.Coordinate coord2 = convertCoordinateToJTS( box.getUpperCorner() );
            polygonArray[i] = JTS.toGeometry( new Envelope( coord1, coord2 ) );
            //LinearRing ring = geometryFactory.createLinearRing( convertCoordinatesToJTS( box.getCoordinates() ) );
            //polygonArray[i] = geometryFactory.createPolygon( ring, new LinearRing[0] );
        } else {
            Polygon polygon = (Polygon) position;
            LinearRing ring = geometryFactory.createLinearRing( convertCoordinatesToJTS( polygon.getCoordinates() ) );
            polygonArray[i] = geometryFactory.createPolygon( ring, new LinearRing[0] );
        }
    }
    return geometryFactory.createMultiPolygon( polygonArray ).toText();
}
 

实例 15


public static String convertToGeometryCollection( Collection<Position> positions ) {
    GeometryFactory geometryFactory = new GeometryFactory();
    com.vividsolutions.jts.geom.Geometry[] geometryArray = new com.vividsolutions.jts.geom.Geometry[positions.size()];
    Iterator<Position> positionIterator = positions.iterator();
    for ( int i = 0; i < positions.size(); i++ ) {
        Position position = (Position) positionIterator.next();
        if ( position instanceof Point ) {
            Point point = (Point) position;
            geometryArray[i] = geometryFactory.createPoint( convertCoordinateToJTS( point.getCoordinate() ) );
        } else if ( position instanceof Line ) {
            Line line = (Line) position;
            geometryArray[i] = geometryFactory.createLineString( convertCoordinatesToJTS( line.getCoordinates() ) );
        } else if ( position instanceof Box ) {
            Box box = (Box) position;
            com.vividsolutions.jts.geom.Coordinate coord1 = convertCoordinateToJTS( box.getLowerCorner() );
            com.vividsolutions.jts.geom.Coordinate coord2 = convertCoordinateToJTS( box.getUpperCorner() );
            geometryArray[i] = JTS.toGeometry( new Envelope( coord1, coord2 ) );
        } else {
            Polygon polygon = (Polygon) position;
            LinearRing ring = geometryFactory.createLinearRing( convertCoordinatesToJTS( polygon.getCoordinates() ) );
            geometryArray[i] = geometryFactory.createPolygon( ring, new LinearRing[0] );
        }
    }
    return geometryFactory.createGeometryCollection( geometryArray ).toText();
}
 
讨论
淘淘あ西西 profile image