Ejemplo n.º 1
0
  protected Geometry transformPolygon(Polygon geom, Geometry parent) {
    boolean isAllValidLinearRings = true;
    Geometry shell = transformLinearRing((LinearRing) geom.getExteriorRing(), geom);

    if (shell == null || !(shell instanceof LinearRing) || shell.isEmpty())
      isAllValidLinearRings = false;
    // return factory.createPolygon(null, null);

    ArrayList holes = new ArrayList();
    for (int i = 0; i < geom.getNumInteriorRing(); i++) {
      Geometry hole = transformLinearRing((LinearRing) geom.getInteriorRingN(i), geom);
      if (hole == null || hole.isEmpty()) {
        continue;
      }
      if (!(hole instanceof LinearRing)) isAllValidLinearRings = false;

      holes.add(hole);
    }

    if (isAllValidLinearRings)
      return factory.createPolygon(
          (LinearRing) shell, (LinearRing[]) holes.toArray(new LinearRing[] {}));
    else {
      List components = new ArrayList();
      if (shell != null) components.add(shell);
      components.addAll(holes);
      return factory.buildGeometry(components);
    }
  }
  @Override
  public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
    if (value != null) {
      Wfs20FeatureCollection wfc = (Wfs20FeatureCollection) value;

      String schemaLoc = generateSchemaLocationFromMetacards(wfc.getMembers(), prefixToUriMapping);

      for (Entry<String, String> entry : prefixToUriMapping.entrySet()) {
        writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + entry.getKey(), entry.getValue());
      }
      writer.addAttribute(Wfs20Constants.ATTRIBUTE_SCHEMA_LOCATION, schemaLoc);

      Geometry allGeometry = getBounds(wfc.getMembers());
      if (!allGeometry.isEmpty()) {
        XmlNode.writeEnvelope(
            Wfs20Constants.GML_PREFIX + ":" + "boundedBy",
            context,
            writer,
            allGeometry.getEnvelopeInternal());
      }

      for (Metacard mc : wfc.getMembers()) {
        writer.startNode(Wfs20Constants.GML_PREFIX + ":" + FEATURE_MEMBER);
        context.convertAnother(mc);
        writer.endNode();
      }
    } else {
      LOGGER.warn("Incoming value was null");
    }
  }
Ejemplo n.º 3
0
  /**
   * Each edge will be built with 2 coordinates.
   *
   * @param intersectingLineStrings The geometry which edges will be based on.
   * @param onLoc position for ON.
   * @param leftLoc position for LEFT.
   * @param rightLoc position for RIGHT.
   */
  private void insertEdge(
      final Geometry intersectingLineStrings,
      final Geometry holeGeometries,
      final int onLoc,
      final int leftLoc,
      final int rightLoc) {

    for (int i = 0; i < intersectingLineStrings.getNumGeometries(); i++) {

      Geometry intersectingSegment = intersectingLineStrings.getGeometryN(i);

      if ((intersectingSegment.getNumPoints() == 2) && !holeGeometries.isEmpty()) {
        // special case, when the line has 2 coordinates and
        // its orientation can't be calculated because it hasn't.
        intersectingSegment = adjustSegmentToHoleDirection(intersectingSegment, holeGeometries);
      }

      Coordinate[] coords = intersectingSegment.getCoordinates();
      for (int j = 0; j < coords.length - 1; j++) {

        final SplitEdge edge =
            SplitEdge.newInstance(coords[j], coords[j + 1], onLoc, leftLoc, rightLoc);

        // add the list that only contains one edge because it will
        // create 2 directedEdge.
        this.graph.addEdge(edge);
      }
    }
  }
 @Override
 protected Envelope getEnvelope(final TestGeometry entry) {
   // incorporate the bounding box of the entry's envelope
   final Geometry geometry = entry.geom;
   if ((geometry != null) && !geometry.isEmpty()) {
     return geometry.getEnvelopeInternal();
   }
   return null;
 }
Ejemplo n.º 5
0
  private void validate(final Geometry geom, final List<ValidationResult> validationErrors) {

    if (geom.isEmpty()) {
      return;
    }

    if (geom instanceof GeometryCollection) {
      final GeometryCollection gc = (GeometryCollection) geom;
      for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) {
        validate(gc.getGeometryN(numGeom), validationErrors);
      }
    }

    final ValidationResult result = new ValidationResult();
    result.setWkt(geom.toText());
    final List<String> messages = new ArrayList<String>();

    if (!geom.isValid()) {
      messages.add("Error en topología básica");
    }

    if (!geom.isSimple()) {
      messages.add("No es una geometría simple");
    }

    if (repeatedPointTester.hasRepeatedPoint(geom)) {
      messages.add("Se encuentran vértices repetidos");
    }

    if (geom instanceof Polygon) {
      final Polygon polygon = (Polygon) geom;
      if (CGAlgorithms.isCCW(polygon.getExteriorRing().getCoordinates())) {
        messages.add("Error en orientación del polígono");
      } else {

        for (int numRing = 0; numRing < polygon.getNumInteriorRing(); numRing++) {
          if (!CGAlgorithms.isCCW(polygon.getInteriorRingN(numRing).getCoordinates())) {
            messages.add("Error en orientación del polígono en anillos interiores");
            break;
          }
        }
      }

      if (!validateMinPolygonArea(geom)) {
        messages.add("Error en validación mínima de area de un polígono");
      }
    }

    if (!validateMinSegmentLength(geom)) {
      messages.add("Error en validación mínima de longitud de segmento");
    }

    if (!messages.isEmpty()) {
      result.setMessages(messages);
      validationErrors.add(result);
    }
  }
Ejemplo n.º 6
0
 protected Geometry transformMultiPolygon(MultiPolygon geom, Geometry parent) {
   List transGeomList = new ArrayList();
   for (int i = 0; i < geom.getNumGeometries(); i++) {
     Geometry transformGeom = transformPolygon((Polygon) geom.getGeometryN(i), geom);
     if (transformGeom == null) continue;
     if (transformGeom.isEmpty()) continue;
     transGeomList.add(transformGeom);
   }
   return factory.buildGeometry(transGeomList);
 }
Ejemplo n.º 7
0
 /**
  * Check if geometry is in SpatialFilter envelopes
  *
  * @param geometry Geometry to check
  * @param envelopes SpatialFilter envelopes
  * @return True if geometry is contained in envelopes
  */
 public boolean featureIsInFilter(final Geometry geometry, final List<Geometry> envelopes) {
   if (geometry != null && !geometry.isEmpty()) {
     for (final Geometry envelope : envelopes) {
       if (envelope.contains(geometry)) {
         return true;
       }
     }
   }
   return false;
 }
Ejemplo n.º 8
0
 private Geometry switchCoordinateAxisIfNeeded(Geometry geometry, int targetSRID)
     throws OwsExceptionReport {
   if (geometry != null && !geometry.isEmpty()) {
     if ((isNorthingFirstEpsgCode(geometry.getSRID()) && isNorthingFirstEpsgCode(targetSRID))
         || (isEastingFirstEpsgCode(geometry.getSRID()) && isEastingFirstEpsgCode(targetSRID))) {
       return geometry;
     }
     return JTSHelper.switchCoordinateAxisOrder(geometry);
   }
   return geometry;
 }
Ejemplo n.º 9
0
 public void encodeGeometryValue(Geometry value, int srid, StringBuffer sql) throws IOException {
   if (value == null || value.isEmpty()) {
     sql.append("ST_GeomFromText ('");
     sql.append(new WKTWriter().write(value));
     sql.append("',");
     sql.append(srid);
     sql.append(")");
   } else {
     sql.append("NULL");
   }
 }
Ejemplo n.º 10
0
 protected Geometry transformGeometryCollection(GeometryCollection geom, Geometry parent) {
   List transGeomList = new ArrayList();
   for (int i = 0; i < geom.getNumGeometries(); i++) {
     Geometry transformGeom = transform(geom.getGeometryN(i));
     if (transformGeom == null) continue;
     if (pruneEmptyGeometry && transformGeom.isEmpty()) continue;
     transGeomList.add(transformGeom);
   }
   if (preserveGeometryCollectionType)
     return factory.createGeometryCollection(GeometryFactory.toGeometryArray(transGeomList));
   return factory.buildGeometry(transGeomList);
 }
Ejemplo n.º 11
0
 /**
  * Transform geometry to this EPSG code
  *
  * @param geometry Geometry to transform
  * @param targetSRID Target EPSG code
  * @return Transformed geometry
  * @throws OwsExceptionReport
  */
 public Geometry transform(final Geometry geometry, final int targetSRID)
     throws OwsExceptionReport {
   if (geometry != null && !geometry.isEmpty()) {
     if (geometry.getSRID() == targetSRID) {
       return geometry;
     }
     CoordinateReferenceSystem sourceCRS = getCRS(geometry.getSRID());
     CoordinateReferenceSystem targetCRS = getCRS(targetSRID);
     return transform(geometry, targetSRID, sourceCRS, targetCRS);
   }
   return geometry;
 }
Ejemplo n.º 12
0
  @Override
  public void encodeGeometryValue(Geometry value, int srid, StringBuffer sql) throws IOException {
    if (value == null || value.isEmpty()) {
      sql.append("NULL");
    } else {
      if (value instanceof LinearRing) {
        // postgis does not handle linear rings, convert to just a line string
        value = value.getFactory().createLineString(((LinearRing) value).getCoordinateSequence());
      }

      sql.append("ST_GeomFromText('" + value.toText() + "', " + srid + ")");
    }
  }
Ejemplo n.º 13
0
 /**
  * Transforms the geometry to the storage EPSG code
  *
  * @param geometry Geometry to transform
  * @return Transformed geometry
  * @throws OwsExceptionReport
  */
 public Geometry transformToStorageEpsg(final Geometry geometry) throws OwsExceptionReport {
   if (geometry != null && !geometry.isEmpty()) {
     CoordinateReferenceSystem sourceCRS = getCRS(geometry.getSRID());
     int targetSRID;
     if (sourceCRS.getCoordinateSystem().getDimension() == 3) {
       targetSRID = getStorage3DEPSG();
     } else {
       targetSRID = getStorageEPSG();
     }
     return transform(geometry, targetSRID, sourceCRS, getCRS(targetSRID));
   }
   return geometry;
 }
Ejemplo n.º 14
0
 public static Rectangle computePixelRegion(
     Product product, Geometry geoRegion, int numBorderPixels) {
   final Geometry productGeometry = computeProductGeometry(product);
   final Geometry regionIntersection = geoRegion.intersection(productGeometry);
   if (regionIntersection.isEmpty()) {
     return new Rectangle();
   }
   final PixelRegionFinder pixelRegionFinder = new PixelRegionFinder(product.getGeoCoding());
   regionIntersection.apply(pixelRegionFinder);
   final Rectangle pixelRegion = pixelRegionFinder.getPixelRegion();
   pixelRegion.grow(numBorderPixels, numBorderPixels);
   return pixelRegion.intersection(
       new Rectangle(product.getSceneRasterWidth(), product.getSceneRasterHeight()));
 }
 public static final int getCoordDim(Geometry geom) {
   if (geom.isEmpty()) {
     return 0;
   }
   if (geom instanceof Point) {
     return getCoordSequenceDim(((Point) geom).getCoordinateSequence());
   } else if (geom instanceof LineString) {
     return getCoordSequenceDim(((LineString) geom).getCoordinateSequence());
   } else if (geom instanceof Polygon) {
     return getCoordSequenceDim(((Polygon) geom).getExteriorRing().getCoordinateSequence());
   } else {
     return getCoordDim(geom.getGeometryN(0));
   }
 }
Ejemplo n.º 16
0
  public static Envelope3D of(final Geometry g) {
    if (g == null || g.isEmpty()) {
      return new Envelope3D();
    }
    final Envelope3D env = new Envelope3D();
    g.apply(
        new CoordinateFilter() {

          @Override
          public void filter(final Coordinate coord) {
            env.expandToInclude(coord);
          }
        });
    return env;
  }
Ejemplo n.º 17
0
 /**
  * Switch the coordinate axis of geometry from or for datasource
  *
  * @param geom Geometry to switch coordinate axis
  * @return Geometry with switched coordinate axis if needed
  * @throws OwsExceptionReport If coordinate axis switching fails
  */
 public Geometry switchCoordinateAxisFromToDatasourceIfNeeded(final Geometry geom)
     throws OwsExceptionReport {
   if (geom != null && !geom.isEmpty()) {
     if (isDatasourceNorthingFirst()) {
       if (!isNorthingFirstEpsgCode(geom.getSRID())) {
         return JTSHelper.switchCoordinateAxisOrder(geom);
       }
       return geom;
     } else {
       if (isNorthingFirstEpsgCode(geom.getSRID())) {
         return JTSHelper.switchCoordinateAxisOrder(geom);
       }
       return geom;
     }
   }
   return geom;
 }
Ejemplo n.º 18
0
  public void write(Geometry geometry, EndianDataOutputStream file) throws IOException {
    if (geometry.isEmpty()) {
      file.writeIntLE(0);
      return;
    }
    file.writeIntLE(getShapeType());
    Coordinate c = geometry.getCoordinates()[0];
    file.writeDoubleLE(c.x);
    file.writeDoubleLE(c.y);

    if (myShapeType == 11) {
      if (Double.isNaN(c.z)) // nan means not defined
      file.writeDoubleLE(0.0);
      else file.writeDoubleLE(c.z);
    }
    if ((myShapeType == 11) || (myShapeType == 21)) {
      file.writeDoubleLE(-10E40); // M
    }
  }
Ejemplo n.º 19
0
  Expression clipToWorld(BinarySpatialOperator filter, Expression e) {
    if (e instanceof Literal) {
      Geometry eval = e.evaluate(filter, Geometry.class);
      // Oracle cannot deal with filters using geometries that span beyond the whole world
      // in case the
      if (dialect != null
          && isCurrentGeometryGeodetic()
          && !WORLD.contains(eval.getEnvelopeInternal())) {
        Geometry result = eval.intersection(JTS.toGeometry(WORLD));

        if (result != null && !result.isEmpty()) {
          if (result instanceof GeometryCollection) {
            result = distillSameTypeGeometries((GeometryCollection) result, eval);
          }
          e = new FilterFactoryImpl().createLiteralExpression(result);
        }
      }
    }
    return e;
  }
 public static int getWKBType(Geometry geom) {
   // We always write emtpy geometries as emtpy collections - for OpenGIS
   // conformance
   if (geom.isEmpty()) {
     return org.postgis.Geometry.GEOMETRYCOLLECTION;
   } else if (geom instanceof Point) {
     return org.postgis.Geometry.POINT;
   } else if (geom instanceof com.vividsolutions.jts.geom.LineString) {
     return org.postgis.Geometry.LINESTRING;
   } else if (geom instanceof com.vividsolutions.jts.geom.Polygon) {
     return org.postgis.Geometry.POLYGON;
   } else if (geom instanceof MultiPoint) {
     return org.postgis.Geometry.MULTIPOINT;
   } else if (geom instanceof MultiLineString) {
     return org.postgis.Geometry.MULTILINESTRING;
   } else if (geom instanceof com.vividsolutions.jts.geom.MultiPolygon) {
     return org.postgis.Geometry.MULTIPOLYGON;
   }
   if (geom instanceof com.vividsolutions.jts.geom.GeometryCollection) {
     return org.postgis.Geometry.GEOMETRYCOLLECTION;
   } else {
     throw new IllegalArgumentException("Unknown Geometry Type: " + geom.getClass().getName());
   }
 }
  @Override
  public void run() {
    /*
     * This tool places the nodes (vertices) from a shapefile of polygons or
     * lines into a shapefile of Point ShapeType.
     */

    amIActive = true;
    String inputFile;
    String outputFile;
    int progress;
    int i, n;
    int numFeatures;
    int oneHundredthTotal;
    ShapeType shapeType, outputShapeType;
    GeometryFactory factory = new GeometryFactory();
    double distTolerance = 10;
    boolean loseNoFeatures = false;

    if (args.length <= 0) {
      showFeedback("Plugin parameters have not been set.");
      return;
    }

    inputFile = args[0];
    outputFile = args[1];
    distTolerance = Double.parseDouble(args[2]);
    loseNoFeatures = Boolean.parseBoolean(args[3]);

    // check to see that the inputHeader and outputHeader are not null.
    if ((inputFile == null) || (outputFile == null)) {
      showFeedback("One or more of the input parameters have not been set properly.");
      return;
    }

    try {
      // set up the input shapefile.
      ShapeFile input = new ShapeFile(inputFile);
      shapeType = input.getShapeType();

      // make sure that the shapetype is either a flavour of polyline or polygon.
      if (shapeType.getBaseType() != ShapeType.POLYGON
          && shapeType.getBaseType() != ShapeType.POLYLINE) {
        showFeedback("This tool only works with shapefiles of a polygon or line base shape type.");
        return;
      }

      // set up the output files of the shapefile and the dbf
      if (shapeType.getBaseType() == ShapeType.POLYGON) {
        outputShapeType = ShapeType.POLYGON;
      } else if (shapeType.getBaseType() == ShapeType.POLYLINE) {
        outputShapeType = ShapeType.POLYLINE;
      } else {
        showFeedback("This tool only works with shapefiles of a polygon or line base shape type.");
        return;
      }

      int numOutputFields = input.getAttributeTable().getFieldCount() + 1;
      int numInputFields = input.getAttributeTable().getFieldCount();
      DBFField[] inputFields = input.getAttributeTable().getAllFields();
      DBFField fields[] = new DBFField[numOutputFields];

      fields[0] = new DBFField();
      fields[0].setName("PARENT_ID");
      fields[0].setDataType(DBFField.DBFDataType.NUMERIC);
      fields[0].setFieldLength(10);
      fields[0].setDecimalCount(0);

      System.arraycopy(inputFields, 0, fields, 1, numInputFields);

      ShapeFile output = new ShapeFile(outputFile, outputShapeType, fields);

      numFeatures = input.getNumberOfRecords();
      oneHundredthTotal = numFeatures / 100;
      n = 0;
      progress = 0;
      com.vividsolutions.jts.geom.Geometry[] recJTS = null;
      int recordNum;
      for (ShapeFileRecord record : input.records) {
        recordNum = record.getRecordNumber();
        Object[] attData = input.getAttributeTable().getRecord(recordNum - 1);
        // featureNum++;
        recJTS = record.getGeometry().getJTSGeometries();

        ArrayList<com.vividsolutions.jts.geom.Geometry> geomList = new ArrayList<>();
        for (int a = 0; a < recJTS.length; a++) {
          geomList.add(recJTS[a]);
        }

        DouglasPeuckerSimplifier dps =
            new DouglasPeuckerSimplifier(factory.buildGeometry(geomList));
        dps.setDistanceTolerance(distTolerance);
        com.vividsolutions.jts.geom.Geometry outputGeom = dps.getResultGeometry();

        if (outputGeom.isEmpty() && loseNoFeatures) {
          outputGeom = factory.buildGeometry(geomList);
        }
        if (!outputGeom.isEmpty()) {
          for (int a = 0; a < outputGeom.getNumGeometries(); a++) {
            // parentRecNum = 0;
            com.vividsolutions.jts.geom.Geometry g = outputGeom.getGeometryN(a);
            if (g instanceof com.vividsolutions.jts.geom.Polygon && !g.isEmpty()) {
              com.vividsolutions.jts.geom.Polygon p = (com.vividsolutions.jts.geom.Polygon) g;
              ArrayList<ShapefilePoint> pnts = new ArrayList<>();
              int[] parts = new int[p.getNumInteriorRing() + 1];

              Coordinate[] buffCoords = p.getExteriorRing().getCoordinates();
              if (!Topology.isLineClosed(buffCoords)) {
                System.out.println("Exterior ring not closed.");
              }
              if (Topology.isClockwisePolygon(buffCoords)) {
                for (i = 0; i < buffCoords.length; i++) {
                  pnts.add(new ShapefilePoint(buffCoords[i].x, buffCoords[i].y));
                }
              } else {
                for (i = buffCoords.length - 1; i >= 0; i--) {
                  pnts.add(new ShapefilePoint(buffCoords[i].x, buffCoords[i].y));
                }
              }

              for (int b = 0; b < p.getNumInteriorRing(); b++) {
                parts[b + 1] = pnts.size();
                buffCoords = p.getInteriorRingN(b).getCoordinates();
                if (!Topology.isLineClosed(buffCoords)) {
                  System.out.println("Interior ring not closed.");
                }
                if (Topology.isClockwisePolygon(buffCoords)) {
                  for (i = buffCoords.length - 1; i >= 0; i--) {
                    pnts.add(new ShapefilePoint(buffCoords[i].x, buffCoords[i].y));
                  }
                } else {
                  for (i = 0; i < buffCoords.length; i++) {
                    pnts.add(new ShapefilePoint(buffCoords[i].x, buffCoords[i].y));
                  }
                }
              }

              PointsList pl = new PointsList(pnts);
              whitebox.geospatialfiles.shapefile.Polygon wbPoly =
                  new whitebox.geospatialfiles.shapefile.Polygon(parts, pl.getPointsArray());
              Object[] rowData = new Object[numOutputFields];
              rowData[0] = new Double(recordNum - 1);
              System.arraycopy(attData, 0, rowData, 1, numInputFields);
              output.addRecord(wbPoly, rowData);
            } else if (g instanceof com.vividsolutions.jts.geom.LineString && !g.isEmpty()) {
              LineString ls = (LineString) g;
              ArrayList<ShapefilePoint> pnts = new ArrayList<>();

              int[] parts = {0};

              Coordinate[] coords = ls.getCoordinates();
              for (i = 0; i < coords.length; i++) {
                pnts.add(new ShapefilePoint(coords[i].x, coords[i].y));
              }

              PointsList pl = new PointsList(pnts);
              whitebox.geospatialfiles.shapefile.PolyLine wbGeometry =
                  new whitebox.geospatialfiles.shapefile.PolyLine(parts, pl.getPointsArray());
              Object[] rowData = new Object[numOutputFields];
              rowData[0] = new Double(recordNum - 1);
              System.arraycopy(attData, 0, rowData, 1, numInputFields);
              output.addRecord(wbGeometry, rowData);
            }
          }
        }
        n++;
        if (n >= oneHundredthTotal) {
          n = 0;
          if (cancelOp) {
            cancelOperation();
            return;
          }
          progress++;
          updateProgress(progress);
        }
      }

      output.write();

      // returning a header file string displays the image.
      updateProgress("Displaying vector: ", 0);
      returnData(outputFile);

    } catch (OutOfMemoryError oe) {
      myHost.showFeedback("An out-of-memory error has occurred during operation.");
    } catch (Exception e) {
      myHost.showFeedback("An error has occurred during operation. See log file for details.");
      myHost.logException("Error in " + getDescriptiveName(), e);
    } finally {
      updateProgress("Progress: ", 0);
      // tells the main application that this process is completed.
      amIActive = false;
      myHost.pluginComplete();
    }
  }
Ejemplo n.º 22
0
  /**
   * Add a feature with layer name (typically feature type name), some attributes and a Geometry.
   * The Geometry must be in "pixel" space 0,0 lower left and 256,256 upper right.
   *
   * <p>For optimization, geometries will be clipped, geometries will simplified and features with
   * geometries outside of the tile will be skipped.
   *
   * @param layerName
   * @param attributes
   * @param geometry
   */
  public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) {

    // split up MultiPolygon and GeometryCollection (without subclasses)
    if (geometry instanceof MultiPolygon || geometry.getClass().equals(GeometryCollection.class)) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // skip small Polygon/LineString.
    if (geometry instanceof Polygon && geometry.getArea() < 1.0d) {
      return;
    }
    if (geometry instanceof LineString && geometry.getLength() < 1.0d) {
      return;
    }

    // clip geometry. polygons right outside. other geometries at tile
    // border.
    try {
      if (geometry instanceof Polygon) {
        Geometry original = geometry;
        geometry = polygonClipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(polygonClipGeometry)) {
          Geometry originalViaWkt = new WKTReader().read(original.toText());
          geometry = polygonClipGeometry.intersection(originalViaWkt);
        }

      } else {
        geometry = clipGeometry.intersection(geometry);
      }
    } catch (TopologyException e) {
      // could not intersect. original geometry will be used instead.
    } catch (ParseException e1) {
      // could not encode/decode WKT. original geometry will be used instead.
    }

    // if clipping result in MultiPolygon, then split once more
    if (geometry instanceof MultiPolygon) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // no need to add empty geometry
    if (geometry.isEmpty()) {
      return;
    }

    Layer layer = layers.get(layerName);
    if (layer == null) {
      layer = new Layer();
      layers.put(layerName, layer);
    }

    Feature feature = new Feature();
    feature.geometry = geometry;

    for (Map.Entry<String, ?> e : attributes.entrySet()) {
      // skip attribute without value
      if (e.getValue() == null) {
        continue;
      }
      feature.tags.add(layer.key(e.getKey()));
      feature.tags.add(layer.value(e.getValue()));
    }

    layer.features.add(feature);
  }
Ejemplo n.º 23
0
 /**
  * Calcuates the record length of this object.
  *
  * @return the length of the record that this point will take up in a shapefile (in WORDS)
  */
 public int getLength(Geometry geometry) {
   if (geometry.isEmpty()) return 2;
   else if (myShapeType == 1) return 10;
   else if (myShapeType == 21) return 14;
   else return 18;
 }
  /** Parse a geometry starting at offset. */
  protected void writeGeometry(Geometry geom, ValueSetter dest) {
    final int dimension;
    if (geom == null) {
      throw new NullPointerException();
    } else if (geom.isEmpty()) {
      // don't set any flag bits
      dimension = 0;
    } else {
      dimension = getCoordDim(geom);
      if (dimension < 2 || dimension > 4) {
        throw new IllegalArgumentException("Unsupported geometry dimensionality: " + dimension);
      }
    }
    // write endian flag
    dest.setByte(dest.endian);

    // write typeword
    final int plaintype = getWKBType(geom);
    int typeword = plaintype;
    if (dimension == 3 || dimension == 4) {
      typeword |= 0x80000000;
    }
    if (dimension == 4) {
      typeword |= 0x40000000;
    }

    final boolean haveSrid = checkSrid(geom);
    if (haveSrid) {
      typeword |= 0x20000000;
    }

    dest.setInt(typeword);

    if (haveSrid) {
      dest.setInt(geom.getSRID());
    }

    switch (plaintype) {
      case org.postgis.Geometry.POINT:
        writePoint((Point) geom, dest);
        break;
      case org.postgis.Geometry.LINESTRING:
        writeLineString((LineString) geom, dest);
        break;
      case org.postgis.Geometry.POLYGON:
        writePolygon((Polygon) geom, dest);
        break;
      case org.postgis.Geometry.MULTIPOINT:
        writeMultiPoint((MultiPoint) geom, dest);
        break;
      case org.postgis.Geometry.MULTILINESTRING:
        writeMultiLineString((MultiLineString) geom, dest);
        break;
      case org.postgis.Geometry.MULTIPOLYGON:
        writeMultiPolygon((MultiPolygon) geom, dest);
        break;
      case org.postgis.Geometry.GEOMETRYCOLLECTION:
        writeCollection((GeometryCollection) geom, dest);
        break;
      default:
        throw new IllegalArgumentException("Unknown Geometry Type: " + plaintype);
    }
  }