Пример #1
0
  private static IPolygon2D createEuclidPolygon(
      final GProjection projection, final com.vividsolutions.jts.geom.Polygon jtsPolygon) {
    final ISimplePolygon2D outerEuclidPolygon =
        createPolygon(jtsPolygon.getCoordinates(), projection);

    final int holesCount = jtsPolygon.getNumInteriorRing();
    if (holesCount == 0) {
      return outerEuclidPolygon;
    }

    final List<ISimplePolygon2D> euclidHoles = new ArrayList<ISimplePolygon2D>(holesCount);
    for (int j = 0; j < holesCount; j++) {
      final com.vividsolutions.jts.geom.LineString jtsHole = jtsPolygon.getInteriorRingN(j);

      try {
        final ISimplePolygon2D euclidHole = createPolygon(jtsHole.getCoordinates(), projection);
        euclidHoles.add(euclidHole);
      } catch (final IllegalArgumentException e) {
        //                              System.err.println(e.getMessage());
      }
    }

    final IPolygon2D euclidPolygon;
    if (euclidHoles.isEmpty()) {
      euclidPolygon = outerEuclidPolygon;
    } else {
      euclidPolygon = new GComplexPolygon2D(outerEuclidPolygon, euclidHoles);
    }
    // System.out.println("Found polygon with " + holesCount + " holes");

    return euclidPolygon;
  }
Пример #2
0
  /**
   * Extract the coordinate arrays for a geometry into a List.
   *
   * @param g the Geometry to extract from
   * @param coordArrayList the List to add the coordinate arrays to
   * @param orientPolygons whether or not the arrays in the List should be oriented (clockwise for
   *     the shell, counterclockwise for the holes)
   */
  public static void addCoordinateArrays(Geometry g, boolean orientPolygons, List coordArrayList) {
    if (g.getDimension() <= 0) {
      return;
    } else if (g instanceof LineString) {
      LineString l = (LineString) g;
      coordArrayList.add(l.getCoordinates());
    } else if (g instanceof Polygon) {
      Polygon poly = (Polygon) g;
      Coordinate[] shell = poly.getExteriorRing().getCoordinates();

      if (orientPolygons) {
        shell = ensureOrientation(shell, CGAlgorithms.CLOCKWISE);
      }

      coordArrayList.add(shell);

      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
        Coordinate[] hole = poly.getInteriorRingN(i).getCoordinates();

        if (orientPolygons) {
          hole = ensureOrientation(hole, CGAlgorithms.COUNTERCLOCKWISE);
        }

        coordArrayList.add(hole);
      }
    } else if (g instanceof GeometryCollection) {
      GeometryCollection gc = (GeometryCollection) g;

      for (int i = 0; i < gc.getNumGeometries(); i++) {
        addCoordinateArrays(gc.getGeometryN(i), orientPolygons, coordArrayList);
      }
    } else {
      Assert.shouldNeverReachHere("Geometry of type " + g.getClass().getName() + " not handled");
    }
  }
Пример #3
0
  /**
   * Converts a JTS {@link Polygon}, which represents a ROI, int an AWT {@link java.awt.Polygon} by
   * means of the provided {@link MathTransform}.
   *
   * <p>It also stores the points for this polygon into the provided {@link List}.
   *
   * @param roiInput the input ROI as a JTS {@link Polygon}.
   * @param worldToGridTransform the {@link MathTransform} to apply to the input ROI.
   * @param points a {@link List} that should hold the transformed points.
   * @return an AWT {@link java.awt.Polygon}.
   * @throws TransformException in case the provided {@link MathTransform} chokes.
   */
  public static java.awt.Polygon convertPolygonToPointArray(
      final Polygon roiInput, MathTransform worldToGridTransform, List<Point2D> points)
      throws TransformException {
    final boolean isIdentity = worldToGridTransform.isIdentity();
    final double coords[] = new double[2];
    final LineString exteriorRing = roiInput.getExteriorRing();
    final CoordinateSequence exteriorRingCS = exteriorRing.getCoordinateSequence();
    final int numCoords = exteriorRingCS.size();
    final java.awt.Polygon retValue = new java.awt.Polygon();
    for (int i = 0; i < numCoords; i++) {
      // get the actual coord
      coords[0] = exteriorRingCS.getX(i);
      coords[1] = exteriorRingCS.getY(i);

      // transform it
      if (!isIdentity) worldToGridTransform.transform(coords, 0, coords, 0, 1);

      // send it back to the returned polygon
      final int x = (int) (coords[0] + 0.5d);
      final int y = (int) (coords[1] + 0.5d);
      if (points != null) points.add(new Point2D.Double(coords[0], coords[1]));

      // send it back to the returned polygon
      retValue.addPoint(x, y);
    }

    // return the created polygon.
    return retValue;
  }
Пример #4
0
  /**
   * Add the given line to the graph
   *
   * @param wrappedLine is MasonGeometry wrapping a JTS line
   * @note Some code copied from JTS PolygonizeGraph.addEdge() and hacked to fit
   */
  private void addLineString(MasonGeometry wrappedLine) {
    LineString line = (LineString) wrappedLine.geometry;

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

    Coordinate[] linePts = CoordinateArrays.removeRepeatedPoints(line.getCoordinates());

    if (linePts.length < 2) {
      return;
    }

    Coordinate startPt = linePts[0];
    Coordinate endPt = linePts[linePts.length - 1];

    Node nStart = getNode(startPt); // nodes added as necessary side-effect
    Node nEnd = getNode(endPt);

    GeomPlanarGraphEdge edge = new GeomPlanarGraphEdge(line);

    GeomPlanarGraphDirectedEdge de0 =
        new GeomPlanarGraphDirectedEdge(nStart, nEnd, linePts[1], true);
    GeomPlanarGraphDirectedEdge de1 =
        new GeomPlanarGraphDirectedEdge(nEnd, nStart, linePts[linePts.length - 2], false);

    edge.setDirectedEdges(de0, de1);

    edge.setAttributes(wrappedLine.getAttributes());

    add(edge);
  }
  /**
   * Sets the Agent up to proceed along an Edge
   *
   * @param edge the GeomPlanarGraphEdge to traverse next
   */
  void setupEdge(GeomPlanarGraphEdge edge) {

    // clean up on old edge
    if (currentEdge != null) {
      ArrayList<AgentCopy> traffic = world.edgeTraffic.get(currentEdge);
      traffic.remove(this);
    }
    currentEdge = edge;

    // update new edge traffic
    if (world.edgeTraffic.get(currentEdge) == null) {
      world.edgeTraffic.put(currentEdge, new ArrayList<AgentCopy>());
    }
    world.edgeTraffic.get(currentEdge).add(this);

    // set up the new segment and index info
    LineString line = edge.getLine();
    segment = new LengthIndexedLine(line);
    startIndex = segment.getStartIndex();
    endIndex = segment.getEndIndex();
    linkDirection = 1;

    // check to ensure that Agent is moving in the right direction
    double distanceToStart = line.getStartPoint().distance(location.geometry),
        distanceToEnd = line.getEndPoint().distance(location.geometry);
    if (distanceToStart <= distanceToEnd) { // closer to start
      currentIndex = startIndex;
      linkDirection = 1;
    } else if (distanceToEnd < distanceToStart) { // closer to end
      currentIndex = endIndex;
      linkDirection = -1;
    }
  }
 private void init(Geometry geom) {
   List lines = LinearComponentExtracter.getLines(geom);
   for (Iterator i = lines.iterator(); i.hasNext(); ) {
     LineString line = (LineString) i.next();
     Coordinate[] pts = line.getCoordinates();
     addLine(pts);
   }
 }
 @Override
 public MultiLineString apply(LineString object) throws UnconvertibleObjectException {
   final MultiLineString geom =
       object.getFactory().createMultiLineString(new LineString[] {object});
   geom.setSRID(object.getSRID());
   geom.setUserData(object.getUserData());
   return geom;
 }
 private int estimateLineString(LineString geom) {
   if (geom == null || geom.getNumGeometries() == 0) {
     return 0;
   } else {
     return 4
         + 8
             * getCoordSequenceDim(geom.getCoordinateSequence())
             * geom.getCoordinateSequence().size();
   }
 }
  /** calculate the length of this street segement from its geometry */
  protected void calculateLengthFromGeometry() {
    double accumulatedMeters = 0;

    LineString geom = getGeometry();

    for (int i = 1; i < geom.getNumPoints(); i++) {
      accumulatedMeters +=
          SphericalDistanceLibrary.distance(geom.getCoordinateN(i - 1), geom.getCoordinateN(i));
    }

    length_mm = (int) (accumulatedMeters * 1000);
  }
 @Test
 public void createComplexGeometryCollectionTest() throws Exception {
   Coordinate ptc = new Coordinate(10, 20);
   Point point = geometryFactory.createPoint(ptc);
   point.setSRID(4326);
   Coordinate[] lsc = new Coordinate[8];
   lsc[0] = new Coordinate(5.0d, 5.0d);
   lsc[1] = new Coordinate(6.0d, 5.0d);
   lsc[2] = new Coordinate(6.0d, 6.0d);
   lsc[3] = new Coordinate(7.0d, 6.0d);
   lsc[4] = new Coordinate(7.0d, 7.0d);
   lsc[5] = new Coordinate(8.0d, 7.0d);
   lsc[6] = new Coordinate(8.0d, 8.0d);
   lsc[7] = new Coordinate(9.0d, 9.0d);
   LineString lineString = geometryFactory.createLineString(lsc);
   lineString.setSRID(4326);
   Coordinate[] lrc = new Coordinate[10];
   lrc[0] = new Coordinate(7, 7);
   lrc[1] = new Coordinate(6, 9);
   lrc[2] = new Coordinate(6, 11);
   lrc[3] = new Coordinate(7, 12);
   lrc[4] = new Coordinate(9, 11);
   lrc[5] = new Coordinate(11, 12);
   lrc[6] = new Coordinate(13, 11);
   lrc[7] = new Coordinate(13, 9);
   lrc[8] = new Coordinate(11, 7);
   lrc[9] = new Coordinate(7, 7);
   LinearRing linearRing = geometryFactory.createLinearRing(lrc);
   linearRing.setSRID(4326);
   Geometry polygon =
       reader.read(
           "POLYGON ((35 10, 10 20, 15 40," + " 45 45, 35 10), (20 30, 35 35, 30 20, 20 30))");
   polygon.setSRID(4326);
   Geometry multiPoint = reader.read("MULTIPOINT ((10 40), (40 30), " + "(20 20), (30 10))");
   multiPoint.setSRID(4326);
   Geometry multiPolygon =
       reader.read(
           "MULTIPOLYGON (((40 40, 20 45,"
               + " 45 30, 40 40)), ((20 35, 45 20, 30 5, "
               + "10 10, 10 30, 20 35), (30 20, 20 25, 20 15, 30 20)))");
   multiPolygon.setSRID(4326);
   GeometryCollection geometryCollection =
       new GeometryCollection(
           new Geometry[] {point, linearRing, lineString, polygon, multiPoint, multiPolygon},
           geometryFactory);
   String geometryCollectionGeoJsonString = mapper.writeValueAsString(geometryCollection);
   logger.info(
       ":::::::::::::::::::::::GEO_JSON_GEOMETRY_COLLECTION : \n{}\n",
       geometryCollectionGeoJsonString);
   org.geojson.GeometryCollection p =
       mapper.readValue(geometryCollectionGeoJsonString, org.geojson.GeometryCollection.class);
   mapper.writeValue(new File("./target/GeometryCollectionComplex.json"), p);
 }
Пример #11
0
  private Geometry intersectionWithSegment(
      Coordinate[] holeCoords, int i, Geometry intersectingSegment) {

    Coordinate[] holeSegmentCoord = new Coordinate[] {holeCoords[i], holeCoords[i + 1]};

    LineString holeSegment;
    GeometryFactory geomFact = intersectingSegment.getFactory();
    holeSegment = geomFact.createLineString(holeSegmentCoord);
    Geometry intersection = holeSegment.intersection(intersectingSegment);

    return intersection;
  }
  static Geometry densify(Geometry geom, CoordinateReferenceSystem crs, double maxAreaError)
      throws FactoryException, TransformException {
    // basic checks
    if (maxAreaError <= 0) {
      throw new IllegalArgumentException("maxAreaError must be greater than 0");
    }
    if (!(geom instanceof Polygon) && !(geom instanceof MultiPolygon)) {
      throw new IllegalArgumentException("Geom must be poligonal");
    }
    if (crs == null) {
      throw new IllegalArgumentException("CRS cannot be set to null");
    }
    double previousArea = 0.0;
    CoordinateReferenceSystem targetCRS = CRS.parseWKT(ECKERT_IV_WKT);
    MathTransform firstTransform = CRS.findMathTransform(crs, targetCRS);
    GeometryFactory geomFactory = new GeometryFactory();
    int ngeom = geom.getNumGeometries();
    Geometry densifiedGeometry = geom;
    double areaError = 1.0d;
    int maxIterate = 0;
    do {
      double max = 0;
      maxIterate++;
      // check the maximum side length of the densifiedGeometry
      for (int j = 0; j < ngeom; j++) {
        Geometry geometry = densifiedGeometry.getGeometryN(j);
        Coordinate[] coordinates = geometry.getCoordinates();
        int n = coordinates.length;
        for (int i = 0; i < (n - 1); i++) {
          Coordinate[] coords = new Coordinate[2];
          coords[0] = coordinates[i];
          coords[1] = coordinates[i + 1];
          LineString lineString = geomFactory.createLineString(coords);
          if (lineString.getLength() > max) max = lineString.getLength();
        }
      }

      // calculate the denified geometry
      densifiedGeometry = Densifier.densify(densifiedGeometry, max / 2);

      // reproject densifiedGeometry to Eckert IV
      Geometry targetGeometry = JTS.transform(densifiedGeometry, firstTransform);
      double nextArea = targetGeometry.getArea();

      // evaluate the current error
      areaError = Math.abs(previousArea - nextArea) / nextArea;
      //      logger3.info("AREA ERROR"+areaError);
      previousArea = nextArea;
      // check whether the current error is greater than the maximum allowed
    } while (areaError > maxAreaError && maxIterate < 10);
    return densifiedGeometry;
  }
Пример #13
0
  private boolean testForUshape(
      Edge edge,
      long maxTime,
      long fromTime,
      long toTime,
      double angleLimit,
      double distanceTolerance,
      double userSpeed,
      boolean hasCar,
      boolean performSpeedTest) {

    LineString ls = (LineString) edge.getGeometry();
    if (ls.getNumPoints() <= 3) { // first filter since u-shapes need at least 4 pts
      // this is the normal case
      return false;
    } else {
      // try to identify u-shapes by checking if the angle EndPoint-StartPoint-StartPoint+1
      // is about 90 degrees (using Azimuths on the sphere)
      double diffTo90Azimuths = 360;
      if (edge instanceof PlainStreetEdge) {
        double firstSegmentAngle = DirectionUtils.getFirstAngle(edge.getGeometry());
        if (firstSegmentAngle < 0) firstSegmentAngle = firstSegmentAngle + Math.PI;
        double firstToLastSegmentAngle = getFirstToLastSegmentAngle(edge.getGeometry());
        if (firstToLastSegmentAngle < 0)
          firstToLastSegmentAngle = firstToLastSegmentAngle + Math.PI;
        double diffAzimuths = Math.abs(firstToLastSegmentAngle - firstSegmentAngle);
        diffTo90Azimuths = Math.abs(diffAzimuths - (Math.PI / 2.0));
      } else {
        // this will happen in particular for transit routes
        // LOG.debug("Edge is not a PlainStreetEdge");
      }
      if (diffTo90Azimuths < angleLimit) {
        // no need to test further if we know its a u-shape
        // System.out.println("u-shape found, (spherical) angle: " + diffTo90Azimuths* 180/Math.PI);
        return true;
      } else {
        if (performSpeedTest) {
          // Use also a distance based criteria since the angle criteria may fail.
          // However a distance based one may fail as well for steep terrain.
          long dt = Math.abs(toTime - fromTime);
          double lineDist = edge.getDistance();
          double distanceToWalkInTimeMissing =
              distanceToMoveInRemainingTime(maxTime, fromTime, dt, userSpeed, edge, hasCar, false);
          double approxWalkableDistanceInTime = distanceToWalkInTimeMissing * distanceTolerance;
          if ((approxWalkableDistanceInTime < lineDist)) {
            return true;
          }
        }
        return false;
      }
    }
  }
Пример #14
0
  /** decimates JTS geometries. */
  public final Geometry decimate(Geometry geom) {
    GeometryFactory gFac = new GeometryFactory(geom.getPrecisionModel(), geom.getSRID());
    if (spanx == -1) return geom;
    if (geom instanceof MultiPoint) {
      // TODO check geometry and if its bbox is too small turn it into a 1
      // point geom
      return geom;
    }
    if (geom instanceof GeometryCollection) {
      // TODO check geometry and if its bbox is too small turn it into a
      // 1-2 point geom
      // takes a bit of work because the geometry will need to be
      // recreated.
      GeometryCollection collection = (GeometryCollection) geom;
      Geometry[] result = new Geometry[collection.getDimension()];
      final int numGeometries = collection.getNumGeometries();
      for (int i = 0; i < numGeometries; i++) {
        result[i] = decimate(collection.getGeometryN(i));
      }
      return gFac.createGeometryCollection(result);

    } else if (geom instanceof LineString) {
      LineString line = (LineString) geom;
      CoordinateSequence seq = (CoordinateSequence) line.getCoordinateSequence();
      LiteCoordinateSequence lseq = new LiteCoordinateSequence(seq.toCoordinateArray());

      if (decimateOnEnvelope(line, lseq)) {
        if (lseq.size() >= 2) return gFac.createLineString(lseq);
      }
      if (lseq.size() >= 2) return gFac.createLineString(decimate(lseq));
      return null;
    } else if (geom instanceof Polygon) {
      Polygon line = (Polygon) geom;
      Coordinate[] exterior = decimate(line.getExteriorRing()).getCoordinates();
      forceClosed(exterior);
      if (exterior.length > 3) {
        LinearRing ring = gFac.createLinearRing(exterior);

        final int numRings = line.getNumInteriorRing();
        List<LinearRing> rings = new ArrayList<LinearRing>();

        for (int i = 0; i < numRings; i++) {
          Coordinate[] interior = decimate(line.getInteriorRingN(i)).getCoordinates();
          forceClosed(interior);
          if (interior.length > 3) rings.add(gFac.createLinearRing(interior));
        }
        return gFac.createPolygon(ring, rings.toArray(new LinearRing[] {}));
      }
      return null;
    }
    return geom;
  }
  /**
   * @param toSplit the line to split
   * @param line the line to use for the split
   * @return a sorted list of geometries as a result of splitting toSplit with line
   */
  protected List<LineString> splitLine(Geometry toSplit, Geometry line) {
    List<LineString> output = new ArrayList();
    Geometry lines = toSplit.union(line);

    for (int i = 0; i < lines.getNumGeometries(); i++) {
      LineString l = (LineString) lines.getGeometryN(i);
      // TODO to be tested
      if (toSplit.contains(l.getInteriorPoint())) {
        output.add(l);
      }
    }
    geometrySorter(output);
    return output;
  }
  private LineString parseLineString(int dimension, CoordinateReferenceSystem crs)
      throws XmlPullParserException, IOException, NoSuchAuthorityCodeException, FactoryException {

    parser.require(START_TAG, GML.NAMESPACE, GML.LineString.getLocalPart());

    crs = crs(crs);
    Coordinate[] coordinates = parseLineStringInternal(dimension, crs);

    parser.require(END_TAG, GML.NAMESPACE, GML.LineString.getLocalPart());

    LineString geom = geomFac.createLineString(coordinates);
    geom.setUserData(crs);
    return geom;
  }
Пример #17
0
  /**
   * Conversion de Jts LineString en Kml LineString
   *
   * @param lineString
   * @return
   */
  private de.micromata.opengis.kml.v_2_2_0.LineString getAsKmlLineString(LineString lineString) {

    de.micromata.opengis.kml.v_2_2_0.LineString kmlLineString =
        new de.micromata.opengis.kml.v_2_2_0.LineString();
    for (int i = 0; i < lineString.getCoordinates().length; i++) {

      Coordinate coordinate = lineString.getCoordinates()[i];
      if (!Double.isNaN(coordinate.z) && !this.forceTo2DGeometry) {
        kmlLineString.addToCoordinates(coordinate.x, coordinate.y, coordinate.z);
      } else {
        kmlLineString.addToCoordinates(coordinate.x, coordinate.y);
      }
    }
    return kmlLineString.withAltitudeMode(AltitudeMode.ABSOLUTE);
  }
Пример #18
0
  public ShapeElemtex(SimpleFeature f, String tipo) {

    super(f, tipo);

    shapeId = "ELEMTEX" + super.newShapeId();

    // Elemtex trae la geometria en formato MultiLineString
    if (f.getDefaultGeometry()
        .getClass()
        .getName()
        .equals("com.vividsolutions.jts.geom.MultiLineString")) {

      MultiLineString l = (MultiLineString) f.getDefaultGeometry();
      LineString line = new LineString(l.getCoordinates(), null, 0);

      coor = line.getEnvelopeInternal().centre();
    } else {
      System.out.println(
          "["
              + new Timestamp(new Date().getTime())
              + "] Formato geometrico "
              + f.getDefaultGeometry().getClass().getName()
              + " desconocido dentro del shapefile ELEMTEX");
    }

    // Los demas atributos son metadatos y de ellos sacamos
    ttggss = (String) f.getAttribute("TTGGSS");

    //		try {
    //			rotulo = new String(f.getAttribute("ROTULO").toString().getBytes(), "UTF-8");
    //			rotulo = eliminarComillas(rotulo);
    //		} catch (UnsupportedEncodingException e) {e.printStackTrace();}

    rotulo = eliminarComillas(f.getAttribute("ROTULO").toString());

    // Dependiendo del ttggss se usa o no
    if (ttggss != null) {
      tags.addAll(ttggssParser(ttggss));
    }

    // Si queremos coger todos los atributos del .shp
    //		this.atributos = new ArrayList<ShapeAttribute>();
    //		for (int x = 1; x < f.getAttributes().size(); x++){
    //			atributos.add(new ShapeAttribute(f.getFeatureType().getDescriptor(x).getType(),
    // f.getAttributes().get(x)));
    //		}

  }
Пример #19
0
 /**
  * Make sure the network doesn't have any problems
  *
  * @param n - the network to be tested
  */
 static void testNetworkForIssues(Network n) {
   System.out.println("testing");
   for (Object o : n.allNodes) {
     GeoNode node = (GeoNode) o;
     for (Object p : n.getEdgesOut(node)) {
       sim.field.network.Edge e = (sim.field.network.Edge) p;
       LineString ls = (LineString) ((MasonGeometry) e.info).geometry;
       Coordinate c1 = ls.getCoordinateN(0);
       Coordinate c2 = ls.getCoordinateN(ls.getNumPoints() - 1);
       GeoNode g1 = (GeoNode) e.getFrom();
       GeoNode g2 = (GeoNode) e.getTo();
       if (c1.distance(g1.geometry.getCoordinate()) > 1) System.out.println("found you");
       if (c2.distance(g2.geometry.getCoordinate()) > 1) System.out.println("found you");
     }
   }
 }
Пример #20
0
  private void treatAndAddUshapeWithinTimeLimits(
      long maxTime,
      double userSpeed,
      ArrayList<LineString> walkShedEdges,
      Edge edge,
      long fromTime,
      long toTime,
      LineString ls,
      boolean hasCar) {

    // check if the u-shape can be traveled within the remaining time
    long dt = Math.abs(toTime - fromTime);
    double distanceToMoveInTimeMissing =
        distanceToMoveInRemainingTime(maxTime, fromTime, dt, userSpeed, edge, hasCar, true);
    double lineDist = edge.getDistance();
    double fraction = (double) distanceToMoveInTimeMissing / (double) lineDist;
    // get the sub-edge geom
    LineString subLine = null;
    if (fraction < 1.0) {
      // the u-shape is not fully walkable in maxTime
      subLine = this.getSubLineString(ls, fraction);
      walkShedEdges.add(subLine);
      // if it is smaller we need also to calculate the LS from the other side
      LineString reversedLine = (LineString) ls.reverse();
      double distanceToMoveInTimeMissing2 =
          distanceToMoveInRemainingTime(maxTime, toTime, dt, userSpeed, edge, hasCar, true);
      double fraction2 = (double) distanceToMoveInTimeMissing2 / (double) lineDist;
      LineString secondsubLine = this.getSubLineString(reversedLine, fraction2);
      ;
      walkShedEdges.add(secondsubLine);
    } else { // the whole u-shape is within the time
      // add only once
      walkShedEdges.add(ls);
    }
  }
Пример #21
0
 /**
  * Creates a circle shape, using the JTS buffer algorithm. The method is used when there is no
  * street found within the given traveltime, e.g. when the pointer is placed on a field or in the
  * woods.<br>
  * TODO: Note it is actually not correct to do buffer calculation in Euclidian 2D, since the
  * resulting shape will be elliptical when projected.
  *
  * @param dropPoint the location given by the user
  * @param pathToStreet the path from the dropPoint to the street, used to retrieve the buffer
  *     distance
  * @return a Circle
  */
 private Geometry createCirle(Coordinate dropPoint, LineString pathToStreet) {
   double length = pathToStreet.getLength();
   GeometryFactory gf = new GeometryFactory();
   Point dp = gf.createPoint(dropPoint);
   Geometry buffer = dp.buffer(length);
   return buffer;
 }
Пример #22
0
  Map<String, Object> createLine(LineString line) {
    LinkedHashMap obj = new LinkedHashMap();

    obj.put("type", "LineString");
    obj.put("coordinates", new CoordinateSequenceEncoder(line.getCoordinateSequence(), scale));
    return obj;
  }
Пример #23
0
  /**
   * ************************************************************************* The method which
   * testing, if the line intersect the triangle
   *
   * @param newL - Geometry of line
   * @return boolean true - line intersect triangle false - line doesn't intersect triangle
   */
  public boolean containsLine(LineString newL) {

    Coordinate[] newPoints = {A, B, C, A};
    CoordinateArraySequence newPointsTriangle = new CoordinateArraySequence(newPoints);
    LinearRing trianglesPoints = new LinearRing(newPointsTriangle, new GeometryFactory());

    return newL.crosses(trianglesPoints.convexHull());
  }
Пример #24
0
 private void init() {
   Coordinate[] pts = parentLine.getCoordinates();
   segs = new TaggedLineSegment[pts.length - 1];
   for (int i = 0; i < pts.length - 1; i++) {
     TaggedLineSegment seg = new TaggedLineSegment(pts[i], pts[i + 1], parentLine, i);
     segs[i] = seg;
   }
 }
Пример #25
0
  @Test
  public void test() throws IOException {
    GeoJSONWriter writer = new GeoJSONWriter();

    Point point = new GeometryFactory().createPoint(new Coordinate(1, 1));
    GeoJSON json = writer.write(point);
    System.out.println(json);

    GeoJSONReader reader = new GeoJSONReader();
    Geometry geometry = reader.read(json);
    System.out.println(geometry);

    LineString lineString =
        new GeometryFactory()
            .createLineString(
                new Coordinate[] {
                  new Coordinate(1, 1),
                  new Coordinate(1, 2),
                  new Coordinate(2, 2),
                  new Coordinate(1, 1)
                });
    json = writer.write(lineString);
    System.out.println(json);

    Polygon polygon = new GeometryFactory().createPolygon(lineString.getCoordinates());
    json = writer.write(polygon);
    System.out.println(json);

    MultiPoint multiPoint = new GeometryFactory().createMultiPoint(lineString.getCoordinates());
    json = writer.write(multiPoint);
    System.out.println(json);

    MultiLineString multiLineString =
        new GeometryFactory().createMultiLineString(new LineString[] {lineString, lineString});
    json = writer.write(multiLineString);
    System.out.println(json);

    MultiPolygon multiPolygon =
        new GeometryFactory().createMultiPolygon(new Polygon[] {polygon, polygon});
    json = writer.write(multiPolygon);
    System.out.println(json);

    geometry = reader.read(json);
    System.out.println(geometry);
  }
Пример #26
0
  public Geometry densify(double segLength) {
    newCoords = new CoordinateList();

    CoordinateSequence seq = inputLine.getCoordinateSequence();

    Coordinate p0 = new Coordinate();
    Coordinate p1 = new Coordinate();
    seq.getCoordinate(0, p0);
    newCoords.add(new Coordinate(p0));

    for (int i = 0; i < seq.size() - 1; i++) {
      seq.getCoordinate(i, p0);
      seq.getCoordinate(i + 1, p1);
      densify(p0, p1, segLength);
    }
    Coordinate[] newPts = newCoords.toCoordinateArray();
    return inputLine.getFactory().createLineString(newPts);
  }
Пример #27
0
  /**
   * Create a new graph, with linestrings read from a shapefile
   *
   * @param shapeFile name of the shapefile containing the network data
   * @throws IOException
   */
  public void addLineStringsFromShape(String shapeFile) throws IOException {
    setLineMergeGraphH4cked(new LineMergeGraphH4cked());
    distancesCalculated = false;
    LineStringReader reader = new LineStringReader(shapeFile);

    reader.read();
    boolean first = true;
    int id = 0;
    for (LineString ls : reader.getLineStrings()) {
      if (first == true) {
        xMax = xMin = ls.getCoordinate().x;
        yMax = yMin = ls.getCoordinate().y;
        first = false;
      }

      addLineString(ls, ++id, (short) 0, (short) 0, 0);
    }
  }
  /**
   * Writes the body for a <code>MultiPolygon</code> object. MultiPolygons are encoded into SVG path
   * elements. This function writes the different polygons in one d-attribute of an SVG path
   * element, separated by an 'M' character. (in other words, it calls the super.writeBody for each
   * polygon).
   *
   * @param o The <code>MultiPolygon</code> to be encoded.
   */
  public void writeObject(Object o, GraphicsDocument document, boolean asChild)
      throws RenderException {
    document.writeElement("path", asChild);
    document.writeAttribute("fill-rule", "evenodd");
    document.writeAttributeStart("d");
    MultiPolygon mpoly = (MultiPolygon) o;
    for (int i = 0; i < mpoly.getNumGeometries(); i++) {
      Polygon poly = (Polygon) mpoly.getGeometryN(i);
      LineString shell = poly.getExteriorRing();
      int nHoles = poly.getNumInteriorRing();
      document.writeClosedPathContent(shell.getCoordinates());

      for (int j = 0; j < nHoles; j++) {
        document.writeClosedPathContent(poly.getInteriorRingN(j).getCoordinates());
      }
    }
    document.writeAttributeEnd();
  }
Пример #29
0
  /** Add a ring to a builder */
  private void addRing(LineString r, Geobuf.Data.Geometry.Builder builder) {
    // skip last point, same as first
    builder.addLengths(r.getNumPoints() - 1);

    long x, y, prevX = 0, prevY = 0;

    // last point is same as first, skip
    for (int i = 0; i < r.getNumPoints() - 1; i++) {
      // delta code
      Coordinate coord = r.getCoordinateN(i);
      // note that roundoff errors do not accumulate
      x = (long) (coord.x * precisionMultiplier);
      y = (long) (coord.y * precisionMultiplier);
      builder.addCoords(x - prevX);
      builder.addCoords(y - prevY);
      prevX = x;
      prevY = y;
    }
  }
Пример #30
0
  /**
   * An approximation to the space surrounding the given meridian.
   *
   * <p>Draws a rhombus (in latitude & longitude space) centered on {@code meridian} from the north
   * pole to the south pole with a small constant width at the equator.
   */
  static Geometry aroundMeridian(double meridian) {
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

    Coordinate northPole = new Coordinate(meridian, MAX_LATITUDE);
    Coordinate equatorEpsilonEast =
        new Coordinate(meridian + MERIDIAN_CROP_WIDTH_AT_EQUATOR, EQUATOR_LATITUDE);
    Coordinate equatorEpsilonWest =
        new Coordinate(meridian - MERIDIAN_CROP_WIDTH_AT_EQUATOR, EQUATOR_LATITUDE);
    Coordinate southPole = new Coordinate(meridian, MIN_LATITUDE);

    LineString easternLine =
        geometryFactory.createLineString(
            new Coordinate[] {northPole, equatorEpsilonEast, southPole});
    LineString westernLine =
        geometryFactory.createLineString(
            new Coordinate[] {northPole, equatorEpsilonWest, southPole});

    return easternLine.union(westernLine).convexHull();
  }