Java Code Examples for org.locationtech.jts.geom.Geometry#setSRID()

The following examples show how to use org.locationtech.jts.geom.Geometry#setSRID() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeopackageCommonDb.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void insertGeometry( String tableName, Geometry geometry, String epsgStr ) throws Exception {
    int epsg = 4326;
    if (epsgStr != null) {
        try {
            epsg = Integer.parseInt(epsgStr);
        } catch (Exception e) {
        }
    }

    IGeometryParser gp = getType().getGeometryParser();
    geometry.setSRID(epsg);
    Object obj = gp.toSqlObject(geometry);
    GeometryColumn gc = getGeometryColumnsForTable(tableName);
    String sql = "INSERT INTO " + tableName + " (" + gc.geometryColumnName + ") VALUES (?)";

    execOnConnection(connection -> {
        try (IHMPreparedStatement pStmt = connection.prepareStatement(sql)) {
            pStmt.setObject(1, obj);
            pStmt.executeUpdate();
        }
        return null;
    });

}
 
Example 2
Source File: H2GisSHPDriver.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object[] getRow(long rowId) throws IOException {
    final int fieldCount = getFieldCount();
    Object[] values = new Object[fieldCount];
    // Copy dbf values
    Object[] dbfValues = dbfDriver.getRow(rowId);
    // Copy dbf values before geometryFieldIndex
    if (geometryFieldIndex > 0) {
        System.arraycopy(dbfValues, 0, values, 0, geometryFieldIndex);
    }
    Geometry geom = shapefileReader.geomAt(shxFileReader.getOffset((int) rowId));
    if (geom != null) {
        geom.setSRID(getSrid());
    }
    values[geometryFieldIndex] = geom;
    // Copy dbf values after geometryFieldIndex
    if (geometryFieldIndex < dbfValues.length) {
        System.arraycopy(dbfValues, geometryFieldIndex, values, geometryFieldIndex + 1, dbfValues.length);
    }
    return values;
}
 
Example 3
Source File: JTSTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link JTS#getCoordinateReferenceSystem(Geometry)}.
 *
 * @throws FactoryException if an EPSG code can not be resolved.
 */
@Test
public void testGetCoordinateReferenceSystem() throws FactoryException {
    final GeometryFactory factory = new GeometryFactory();
    final Geometry geometry = factory.createPoint(new Coordinate(5, 6));

    CoordinateReferenceSystem crs = JTS.getCoordinateReferenceSystem(geometry);
    assertNull(crs);
    /*
     * Test CRS as user data.
     */
    geometry.setUserData(CommonCRS.ED50.geographic());
    assertEquals(CommonCRS.ED50.geographic(), JTS.getCoordinateReferenceSystem(geometry));
    /*
     * Test CRS as map value.
     */
    geometry.setUserData(Collections.singletonMap(JTS.CRS_KEY, CommonCRS.NAD83.geographic()));
    assertEquals(CommonCRS.NAD83.geographic(), JTS.getCoordinateReferenceSystem(geometry));
    /*
     * Test CRS as srid.
     */
    geometry.setUserData(null);
    geometry.setSRID(4326);
    assertEquals(CommonCRS.WGS84.geographic(), JTS.getCoordinateReferenceSystem(geometry));
}
 
Example 4
Source File: GmlDecoderv321.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private Geometry parseCompositeSurfaceType(CompositeSurfaceType xbCompositeSurface) throws DecodingException {
    SurfacePropertyType[] xbCurfaceProperties = xbCompositeSurface.getSurfaceMemberArray();
    int srid = -1;
    ArrayList<Polygon> polygons = new ArrayList<>(xbCurfaceProperties.length);
    if (xbCompositeSurface.getSrsName() != null) {
        srid = CRSHelper.parseSrsName(xbCompositeSurface.getSrsName());
    }
    for (SurfacePropertyType xbSurfaceProperty : xbCurfaceProperties) {
        AbstractSurfaceType xbAbstractSurface = xbSurfaceProperty.getAbstractSurface();
        if (srid == -1 && xbAbstractSurface.getSrsName() != null) {
            srid = CRSHelper.parseSrsName(xbAbstractSurface.getSrsName());
        }
        if (xbAbstractSurface instanceof PolygonType) {
            polygons.add((Polygon) parsePolygonType((PolygonType) xbAbstractSurface));
        } else {
            throw new DecodingException("The FeatureType %s is not supportted! Only PolygonType",
                                        xbAbstractSurface);
        }
    }
    if (polygons.isEmpty()) {
        throw new DecodingException("The FeatureType: %s does not contain any member!", xbCompositeSurface);
    }
    srid = setDefaultForUnsetSrid(srid);
    GeometryFactory factory = new GeometryFactory();
    Geometry geom = factory.createMultiPolygon(polygons.toArray(new Polygon[polygons.size()]));
    geom.setSRID(srid);
    return geom;
}
 
Example 5
Source File: PostgisGeometryParser.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private synchronized Geometry getGeom( PGgeometry pgGeometry ) throws SQLException, ParseException {
    String wkt = pgGeometry.toString();
    String[] splitSRID = PGgeometry.splitSRID(wkt);
    Geometry geometry = wktReader.read(splitSRID[1]);
    try {
        int srid = Integer.parseInt(splitSRID[0].substring(5));
        geometry.setSRID(srid);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return geometry;
}
 
Example 6
Source File: GeoPkgGeomReader.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
protected Geometry read() throws IOException { // header must be read!
    // read the geometry
    try {
        WKBReader wkbReader = new WKBReader(factory);
        Geometry g = wkbReader.read(input);
        g.setSRID(header.getSrid());
        return g;
    } catch (ParseException e) {
        throw new IOException(e);
    }
}
 
Example 7
Source File: GeometryAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public G unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom.getSRID() == 0)
        the_geom.setSRID(4326);

    try {
        return (G) the_geom;
    } catch (ClassCastException e) {
        throw new ParseException("WKT val is a " + the_geom.getClass().getName());
    }
}
 
Example 8
Source File: PolygonAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Polygon unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom instanceof Polygon) {
        if (the_geom.getSRID() == 0)
            the_geom.setSRID(4326);

        return (Polygon) the_geom;
    }

    throw new ParseException("WKB val is not a Polygon.");
}
 
Example 9
Source File: XMultiPolygonAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public MultiPolygon unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom.getSRID() == 0)
        the_geom.setSRID(4326);

    try {
        return (MultiPolygon) the_geom;
    } catch (ClassCastException e) {
        throw new ParseException("WKT val is a " + the_geom.getClass().getName());
    }
}
 
Example 10
Source File: SimpleFeatureGeometryExtractor.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public Geometry getGeometry(final SimpleFeature anObject) {
  final FeatureGeometryHandler handler =
      new FeatureGeometryHandler(anObject.getDefaultGeometryProperty().getDescriptor());
  final Geometry geometry = handler.toIndexValue(anObject).getGeometry();
  final int srid = getSRID(anObject);
  geometry.setSRID(srid);
  return geometry;
}
 
Example 11
Source File: JTS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Copies coordinate reference system information from the given source geometry to the target geometry.
 * Current implementation copies only CRS information, but future implementations could copy some other
 * values if they may apply to the target geometry as well.
 */
private static void copyMetadata(final Geometry source, final Geometry target) {
    target.setSRID(source.getSRID());
    Object crs = source.getUserData();
    if (!(crs instanceof CoordinateReferenceSystem)) {
        if (!(crs instanceof Map<?,?>)) {
            return;
        }
        crs = ((Map<?,?>) crs).get(org.apache.sis.internal.feature.jts.JTS.CRS_KEY);
        if (!(crs instanceof CoordinateReferenceSystem)) {
            return;
        }
    }
    target.setUserData(crs);
}
 
Example 12
Source File: GeopackageTableLayer.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
private void updateGeometry(ASpatialDb db, String tableName, long id, Geometry geometry) throws Exception {
    int epsg = 4326;
    String pk = ((GPGeopackageDb) db).getPrimaryKey(tableName);

    IGeometryParser gp = db.getType().getGeometryParser();
    geometry.setSRID(epsg);
    Object obj = gp.toSqlObject(geometry);
    if (obj instanceof byte[]) {
        byte[] objBytes = (byte[]) obj;
        GeometryColumn gc = db.getGeometryColumnsForTable(tableName);
        String sql = "update " + tableName + " set " + gc.geometryColumnName + "=? where " + pk + "=" + id;

        db.execOnConnection(connection -> {
            try (IHMPreparedStatement pStmt = connection.prepareStatement(sql)) {
                pStmt.setBytes(1, objBytes);
                pStmt.executeUpdate();
            }
            return null;
        });

        Envelope env = geometry.getEnvelopeInternal();
        double minX = env.getMinX();
        double maxX = env.getMaxX();
        double minY = env.getMinY();
        double maxY = env.getMaxY();

        try {
            // also update rtree index, since it is not supported
            String sqlTree = "INSERT OR REPLACE INTO rtree_" + tableName + "_" + gc.geometryColumnName +
                    " VALUES (" + id + "," + minX + ", " + maxX + "," + minY + ", " + maxY + ");";
            db.executeInsertUpdateDeleteSql(sqlTree);
        } catch (Exception e) {
            GPLog.error(this, "ERROR on rtree", e);
        }

    } else {
        throw new IllegalArgumentException("Geometry object is not byte array.");
    }
}
 
Example 13
Source File: ASpatialDb.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get the geometries of a table intersecting a given geometry.
 * 
 * @param tableName
 *            the table name.
 * @param intersectionGeometry
 *            the geometry to check, assumed in the same srid of the table geometry.
 * @param prePostWhere an optional set of 3 parameters. The parameters are: a 
 *          prefix wrapper for geom, a postfix for the same and a where string 
 *          to apply. They all need to be existing if the parameter is passed.
 * @return The list of geometries intersecting the geometry.
 * @throws Exception
 */
public List<Geometry> getGeometriesIn( String tableName, Geometry intersectionGeometry, String... prePostWhere )
        throws Exception {
    List<Geometry> geoms = new ArrayList<Geometry>();

    List<String> wheres = new ArrayList<>();
    String pre = "";
    String post = "";
    String where = "";
    if (prePostWhere != null && prePostWhere.length == 3) {
        if (prePostWhere[0] != null)
            pre = prePostWhere[0];
        if (prePostWhere[1] != null)
            post = prePostWhere[1];
        if (prePostWhere[2] != null) {
            where = prePostWhere[2];
            wheres.add(where);
        }
    }
    GeometryColumn gCol = getGeometryColumnsForTable(tableName);
    String sql = "SELECT " + pre + gCol.geometryColumnName + post + " FROM " + DbsUtilities.fixTableName(tableName);

    if (intersectionGeometry != null && supportsSpatialIndex) {
        intersectionGeometry.setSRID(gCol.srid);
        String spatialindexGeometryWherePiece = getSpatialindexGeometryWherePiece(tableName, null, intersectionGeometry);
        if (spatialindexGeometryWherePiece != null)
            wheres.add(spatialindexGeometryWherePiece);
    }

    if (wheres.size() > 0) {
        sql += " WHERE " + DbsUtilities.joinBySeparator(wheres, " AND ");
    }

    IGeometryParser geometryParser = getType().getGeometryParser();
    String _sql = sql;
    return execOnConnection(connection -> {
        PreparedGeometry prepGeom = null;
        if (!supportsSpatialIndex) {
            prepGeom = PreparedGeometryFactory.prepare(intersectionGeometry);
        }
        try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(_sql)) {
            while( rs.next() ) {
                Geometry geometry = geometryParser.fromResultSet(rs, 1);
                if (prepGeom != null && !prepGeom.intersects(geometry)) {
                    continue;
                }
                geoms.add(geometry);
            }
            return geoms;
        }
    });

}
 
Example 14
Source File: TestUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static Object fromWkt( String wkt, ASpatialDb db ) throws Exception {
    IGeometryParser gp = db.getType().getGeometryParser();
    Geometry geometry = new WKTReader().read(wkt);
    geometry.setSRID(4326);
    return gp.toSqlObject(geometry);
}
 
Example 15
Source File: GeopackageTableLayer.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
private long insertGeometry(ASpatialDb db, String tableName, Geometry geometry) throws Exception {
    int epsg = 4326;
    String pk = ((GPGeopackageDb) db).getPrimaryKey(tableName);
    long nextId = db.getLong("select max(" + pk + ") from " + tableName) + 1;

    IGeometryParser gp = db.getType().getGeometryParser();
    geometry.setSRID(epsg);
    Object obj = gp.toSqlObject(geometry);
    if (obj instanceof byte[]) {
        byte[] objBytes = (byte[]) obj;
        GeometryColumn gc = db.getGeometryColumnsForTable(tableName);
        String sql = "INSERT INTO " + tableName + " (" + pk + "," + gc.geometryColumnName + ") VALUES (?, ?)";

        db.execOnConnection(connection -> {
            try (IHMPreparedStatement pStmt = connection.prepareStatement(sql)) {
                pStmt.setLong(1, nextId);
                pStmt.setBytes(2, objBytes);
                pStmt.executeUpdate();
            }
            return null;
        });

        Envelope env = geometry.getEnvelopeInternal();
        double minX = env.getMinX();
        double maxX = env.getMaxX();
        double minY = env.getMinY();
        double maxY = env.getMaxY();

        try {
            // also update rtree index, since it is not supported
            String sqlTree = "INSERT OR REPLACE INTO rtree_" + tableName + "_" + gc.geometryColumnName +
                    " VALUES (" + nextId + "," + minX + ", " + maxX + "," + minY + ", " + maxY + ");";
            db.executeInsertUpdateDeleteSql(sqlTree);
        } catch (Exception e) {
            GPLog.error(this, "ERROR on rtree", e);
        }

        return nextId;
    }

    throw new IllegalArgumentException("Geometry object is not byte array.");
}
 
Example 16
Source File: SpatialiteWKBReader.java    From hortonmachine with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Sets the SRID, if it was specified in the WKB
 *
 * @param g the geometry to update
 * @return the geometry with an updated SRID value, if required
 */
private Geometry setSRID( Geometry g, int SRID ) {
    if (SRID != 0)
        g.setSRID(SRID);
    return g;
}