protected Polygon toPolygon(ReferencedEnvelope env2) {
    ReferencedEnvelope env = env2;
    if (env == null) env = new ReferencedEnvelope(-180, 180, -90, 90, DefaultGeographicCRS.WGS84);

    AttributeDescriptor att = mapper.getSchema().getDescriptor(mapper.getBounds());
    CoordinateReferenceSystem crs = null;

    if (att instanceof GeometryDescriptor)
      crs = ((GeometryDescriptor) att).getCoordinateReferenceSystem();

    if (crs == null) crs = DefaultGeographicCRS.WGS84;

    GeometryFactory factory = new GeometryFactory();
    try {
      env = env.transform(crs, true);
    } catch (Exception e) {
      IssuesActivator.log("", e); // $NON-NLS-1$
    }

    return factory.createPolygon(
        factory.createLinearRing(
            new Coordinate[] {
              new Coordinate(env.getMinX(), env.getMinY()),
              new Coordinate(env.getMaxX(), env.getMinY()),
              new Coordinate(env.getMaxX(), env.getMaxY()),
              new Coordinate(env.getMinX(), env.getMaxY()),
              new Coordinate(env.getMinX(), env.getMinY()),
            }),
        new LinearRing[0]);
  }
Esempio n. 2
0
  private void updateGeometry() {
    final List<Geometry> geoms = new ArrayList<>();
    if (coords.size() == 1) {
      // single point
      final Geometry geom = GEOMETRY_FACTORY.createPoint(coords.get(0));
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    } else if (coords.size() == 2) {
      // line
      final Geometry geom =
          GEOMETRY_FACTORY.createLineString(coords.toArray(new Coordinate[coords.size()]));
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    } else if (coords.size() > 2) {
      // polygon
      final Coordinate[] ringCoords = coords.toArray(new Coordinate[coords.size() + 1]);
      ringCoords[coords.size()] = coords.get(0);
      final LinearRing ring = GEOMETRY_FACTORY.createLinearRing(ringCoords);
      final Geometry geom = GEOMETRY_FACTORY.createPolygon(ring, new LinearRing[0]);
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    }
    layer.getGeometries().setAll(geoms);

    if (geoms.isEmpty()) {
      uiArea.setText("-");
    } else {
      uiArea.setText(
          NumberFormat.getNumberInstance()
              .format(
                  MeasureUtilities.calculateArea(
                      geoms.get(0), map.getCanvas().getObjectiveCRS2D(), uiUnit.getValue())));
    }
  }
  private SimpleFeature createPolyFeature(
      int startx,
      int starty,
      int width,
      int height,
      String name,
      CoordinateReferenceSystem crs,
      GeometryFactory geomFac)
      throws Exception {
    Coordinate[] c =
        new Coordinate[] {
          new Coordinate(startx, starty),
          new Coordinate(startx + width, starty),
          new Coordinate(startx + width, starty + height),
          new Coordinate(startx, starty),
        };
    LinearRing line = geomFac.createLinearRing(c);
    Polygon poly = geomFac.createPolygon(line, null);

    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    if (crs != null) builder.add("polygon", poly.getClass(), crs);
    else builder.add("centre", line.getClass());
    builder.add("name", String.class);
    builder.setName(Rendering2DTest.POLYGON);
    SimpleFeatureType type = builder.buildFeatureType();
    return SimpleFeatureBuilder.build(type, new Object[] {poly, name}, null);
  }
Esempio n. 4
0
  public void testBounds() throws Exception {
    PrecisionModel pm = new PrecisionModel();
    Geometry[] g = new Geometry[4];
    GeometryFactory gf = new GeometryFactory(pm);

    g[0] = gf.createPoint(new Coordinate(0, 0));
    g[1] = gf.createPoint(new Coordinate(0, 10));
    g[2] = gf.createPoint(new Coordinate(10, 0));
    g[3] = gf.createPoint(new Coordinate(10, 10));

    GeometryCollection gc = gf.createGeometryCollection(g);

    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("bounds");
    tb.setCRS(null);
    tb.add("p1", Point.class);

    SimpleFeatureType t = tb.buildFeatureType();

    TreeSetFeatureCollection fc = new TreeSetFeatureCollection(null, t);
    SimpleFeatureBuilder b = new SimpleFeatureBuilder(t);
    for (int i = 0; i < g.length; i++) {
      b.add(g[i]);
      fc.add(b.buildFeature(null));
    }
    assertEquals(gc.getEnvelopeInternal(), fc.getBounds());
  }
 @Override
 public SimpleFeature decode(String recordId, String[] csvRecord) {
   SimpleFeatureType featureType = getFeatureType();
   SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
   GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
   GeometryFactory geometryFactory = new GeometryFactory();
   Double lat = null, lng = null;
   String[] headers = csvFileState.getCSVHeaders();
   for (int i = 0; i < headers.length; i++) {
     String header = headers[i];
     if (i < csvRecord.length) {
       String value = csvRecord[i].trim();
       if (geometryDescriptor != null && header.equals(latField)) {
         lat = Double.valueOf(value);
       } else if (geometryDescriptor != null && header.equals(lngField)) {
         lng = Double.valueOf(value);
       } else {
         builder.set(header, value);
       }
     } else {
       builder.set(header, null);
     }
   }
   if (geometryDescriptor != null && lat != null && lng != null) {
     Coordinate coordinate = new Coordinate(lng, lat);
     Point point = geometryFactory.createPoint(coordinate);
     builder.set(geometryDescriptor.getLocalName(), point);
   }
   return builder.buildFeature(csvFileState.getTypeName() + "-" + recordId);
 }
Esempio n. 6
0
  public <T> T evaluate(Object object, Class<T> context) {
    Point point;
    Expression param1 = parameters.get(0);

    if (param1.equals(ToDirectPositionFunction.SRS_NAME)) {

      if (parameters.size() > 5 || parameters.size() < 4) {
        throw new IllegalArgumentException(
            "Wrong number of parameters for toPoint function: "
                + parameters.toString()
                + ". Usage: toPoint('SRS_NAME'(optional), srsName(optional), point 1, point 2, gml:id(optional))");
      }
      CoordinateReferenceSystem crs = null;
      String srsName = parameters.get(1).evaluate(object, String.class);
      try {
        crs = CRS.decode((String) srsName);
      } catch (NoSuchAuthorityCodeException e) {
        throw new IllegalArgumentException(
            "Invalid or unsupported SRS name detected for toPoint function: "
                + srsName
                + ". Cause: "
                + e.getMessage());
      } catch (FactoryException e) {
        throw new RuntimeException("Unable to decode SRS name. Cause: " + e.getMessage());
      }
      GeometryFactory fac = new GeometryFactory(new PrecisionModel());
      point =
          fac.createPoint(
              new Coordinate(
                  parameters.get(2).evaluate(object, Double.class),
                  parameters.get(3).evaluate(object, Double.class)));
      // set attributes
      String gmlId = null;
      if (parameters.size() == 5) {
        gmlId = parameters.get(4).evaluate(object, String.class);
      }
      setUserData(point, crs, gmlId);
    } else {

      if (parameters.size() > 3 || parameters.size() < 2) {
        throw new IllegalArgumentException(
            "Wrong number of parameters for toPoint function: "
                + parameters.toString()
                + ". Usage: toPoint('SRS_NAME'(optional), srsName(optional), point 1, point 2, gml:id(optional))");
      }
      GeometryFactory fac = new GeometryFactory();

      point =
          fac.createPoint(
              new Coordinate(
                  param1.evaluate(object, Double.class),
                  parameters.get(1).evaluate(object, Double.class)));

      if (parameters.size() == 3) {
        String gmlId = parameters.get(2).evaluate(object, String.class);
        setUserData(point, null, gmlId);
      }
    }
    return (T) point;
  }
  /**
   * Creates a elliptical arc, as a LineString.
   *
   * @return an elliptical arc
   */
  public LineString createArc(double startAng, double endAng) {
    Envelope env = dim.getEnvelope();
    double xRadius = env.getWidth() / 2.0;
    double yRadius = env.getHeight() / 2.0;

    double centreX = env.getMinX() + xRadius;
    double centreY = env.getMinY() + yRadius;

    double angSize = (endAng - startAng);
    if (angSize <= 0.0 || angSize > 2 * Math.PI) angSize = 2 * Math.PI;
    double angInc = angSize / nPts;

    Coordinate[] pts = new Coordinate[nPts];
    int iPt = 0;
    for (int i = 0; i < nPts; i++) {
      double ang = startAng + i * angInc;
      double x = xRadius * Math.cos(ang) + centreX;
      double y = yRadius * Math.sin(ang) + centreY;
      Coordinate pt = new Coordinate(x, y);
      geomFact.getPrecisionModel().makePrecise(pt);
      pts[iPt++] = pt;
    }
    LineString line = geomFact.createLineString(pts);
    return line;
  }
Esempio n. 8
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);
    }
  }
Esempio n. 9
0
  private FeatureCollection convexHhull(TaskMonitor monitor, FeatureCollection fc) {
    monitor.allowCancellationRequests();
    monitor.report(I18N.get("ui.plugin.analysis.ConvexHullPlugIn.Computing-Convex-Hull") + "...");

    int size = fc.size();
    GeometryFactory geomFact = null;

    if (size == 0) {
      return null;
    }
    int count = 0;
    Geometry[] geoms = new Geometry[size];

    for (Iterator i = fc.iterator(); i.hasNext(); ) {
      Feature f = (Feature) i.next();
      Geometry geom = f.getGeometry();
      if (geom == null) {
        continue;
      }
      if (geomFact == null) {
        geomFact = geom.getFactory();
      }

      geoms[count++] = geom;
    }
    GeometryCollection gc = geomFact.createGeometryCollection(geoms);
    Geometry hull = gc.convexHull();
    List hullList = new ArrayList();
    hullList.add(hull);

    return FeatureDatasetFactory.createFromGeometry(hullList);
  }
  public void testHomogeneous() throws Exception {
    Node node =
        createNode(
            gcol,
            new ElementInstance[] {point1, point2},
            new Object[] {
              gf.createPoint(new Coordinate(0, 0)), gf.createPoint(new Coordinate(1, 1))
            },
            null,
            null);

    GMLGeometryCollectionTypeBinding s =
        (GMLGeometryCollectionTypeBinding)
            container.getComponentInstanceOfType(GMLGeometryCollectionTypeBinding.class);

    GeometryCollection gc = (GeometryCollection) s.parse(gcol, node, null);
    assertNotNull(gc);
    assertEquals(gc.getNumGeometries(), 2);
    assertTrue(gc.getGeometryN(0) instanceof Point);
    assertTrue(gc.getGeometryN(1) instanceof Point);
    assertEquals(((Point) gc.getGeometryN(0)).getX(), 0d, 0d);
    assertEquals(((Point) gc.getGeometryN(0)).getY(), 0d, 0d);
    assertEquals(((Point) gc.getGeometryN(1)).getX(), 1d, 0d);
    assertEquals(((Point) gc.getGeometryN(1)).getY(), 1d, 0d);
  }
Esempio n. 11
0
  private void addMetacardLocation(
      final XstreamPathValueTracker pathValueTracker, MetacardImpl metacard) {
    String westLon = pathValueTracker.getPathValue(BBOX_WEST_LON_PATH);
    String eastLon = pathValueTracker.getPathValue(BBOX_EAST_LON_PATH);
    String southLat = pathValueTracker.getPathValue(BBOX_SOUTH_LAT_PATH);
    String northLat = pathValueTracker.getPathValue(BBOX_NORTH_LAT_PATH);

    if (westLon != null && eastLon != null && southLat != null && northLat != null) {
      WKTWriter wktWriter = new WKTWriter();

      GeometryFactory factory = new GeometryFactory();
      try {
        Envelope envelope =
            new Envelope(
                Double.parseDouble(eastLon.trim()),
                Double.parseDouble(westLon.trim()),
                Double.parseDouble(southLat.trim()),
                Double.parseDouble(northLat.trim()));
        String wkt = wktWriter.write(factory.toGeometry(envelope));
        if (wkt != null) {
          metacard.setLocation(wkt);
        }
      } catch (NumberFormatException nfe) {
        LOGGER.info(
            "Unable to parse double from GMD metadata {}, {}, {}, {}",
            westLon,
            eastLon,
            southLat,
            northLat);
      }
    }
  }
Esempio n. 12
0
  /**
   * Return the ListEdge in the road network which is closest to the given coordinate, within the
   * given resolution
   *
   * @param c
   * @param resolution
   * @return
   */
  public ListEdge getClosestEdge(Coordinate c, double resolution) {

    // find the set of all edges within *resolution* of the given point
    Bag objects = networkEdgeLayer.getObjectsWithinDistance(fa.createPoint(c), resolution);
    if (objects == null || networkEdgeLayer.getGeometries().size() <= 0)
      return null; // problem with the network edge layer

    Point point = fa.createPoint(c);

    // find the closest edge among the set of edges
    double bestDist = resolution;
    ListEdge bestEdge = null;
    for (Object o : objects) {
      double dist = ((MasonGeometry) o).getGeometry().distance(point);
      if (dist < bestDist) {
        bestDist = dist;
        bestEdge =
            (ListEdge) ((AttributeValue) ((MasonGeometry) o).getAttribute("ListEdge")).getValue();
      }
    }

    // if it exists, return it
    if (bestEdge != null) return bestEdge;

    // otherwise return failure
    else return null;
  }
Esempio n. 13
0
  public void testEqualsExactForGeometryCollections() throws Exception {
    Geometry polygon1 = (Polygon) reader.read("POLYGON ((0 0, 0 50, 50 50, 50 0, 0 0))");
    Geometry polygon2 = (Polygon) reader.read("POLYGON ((50 50, 50 0, 0 0, 0 50, 50 50))");
    GeometryCollection x =
        geometryFactory.createGeometryCollection(new Geometry[] {polygon1, polygon2});
    GeometryCollection somethingExactlyEqual =
        geometryFactory.createGeometryCollection(new Geometry[] {polygon1, polygon2});
    GeometryCollection somethingNotEqualButSameClass =
        geometryFactory.createGeometryCollection(new Geometry[] {polygon2});
    GeometryCollection sameClassButEmpty = geometryFactory.createGeometryCollection(null);
    GeometryCollection anotherSameClassButEmpty = geometryFactory.createGeometryCollection(null);
    CollectionFactory collectionFactory =
        new CollectionFactory() {
          public Geometry createCollection(Geometry[] geometries) {
            return geometryFactory.createGeometryCollection(geometries);
          }
        };

    doTestEqualsExact(
        x,
        somethingExactlyEqual,
        somethingNotEqualButSameClass,
        sameClassButEmpty,
        anotherSameClassButEmpty,
        collectionFactory);
  }
 private EXGeographicBoundingBox getGeographicBoundingBox(Envelope env, String epsgCode) {
   Envelope newEnvelope;
   if ("EPSG:4326".equals(epsgCode)) {
     newEnvelope = env;
   } else {
     try {
       GeometryFactory gf = new GeometryFactory();
       Polygon poly = (Polygon) gf.toGeometry(env);
       ST_Transform transformFunction = new ST_Transform();
       CoordinateReferenceSystem inputCRS = DataSourceFactory.getCRSFactory().getCRS(epsgCode);
       Value val =
           transformFunction.evaluate(
               null,
               ValueFactory.createValue(poly, inputCRS),
               ValueFactory.createValue("EPSG:4326"));
       newEnvelope = val.getAsGeometry().getEnvelopeInternal();
     } catch (FunctionException fe) {
       return getDummyGeographic();
     } catch (CRSException ex) {
       return getDummyGeographic();
     }
   }
   EXGeographicBoundingBox ret = new EXGeographicBoundingBox();
   ret.setEastBoundLongitude(newEnvelope.getMaxX());
   ret.setWestBoundLongitude(newEnvelope.getMinX());
   ret.setNorthBoundLatitude(newEnvelope.getMaxY());
   ret.setSouthBoundLatitude(newEnvelope.getMinY());
   return ret;
 }
Esempio n. 15
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;
 }
Esempio n. 16
0
  @Test
  public void testLenght() throws NoSuchIdentifierException, ProcessException {

    GeometryFactory fact = new GeometryFactory();

    // Inputs first
    final LinearRing ring =
        fact.createLinearRing(
            new Coordinate[] {
              new Coordinate(0.0, 0.0),
              new Coordinate(0.0, 10.0),
              new Coordinate(5.0, 10.0),
              new Coordinate(5.0, 0.0),
              new Coordinate(0.0, 0.0)
            });

    final Geometry geom1 = fact.createPolygon(ring, null);

    // Process
    final ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("jts", "lenght");

    final ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("geom").setValue(geom1);
    final org.geotoolkit.process.Process proc = desc.createProcess(in);

    // result
    final Double result = (Double) proc.call().parameter("result").getValue();

    final Double expected = geom1.getLength();

    assertTrue(expected.equals(result));
  }
Esempio n. 17
0
  public LineString createGeometry(Vertex a, Vertex b) {

    GeometryFactory factory = new GeometryFactory();
    Coordinate[] cs = new Coordinate[2];
    cs[0] = a.getCoordinate();
    cs[1] = b.getCoordinate();
    return factory.createLineString(cs);
  }
Esempio n. 18
0
 /**
  * Transforms a LinearRing. The transformation of a LinearRing may result in a coordinate sequence
  * which does not form a structurally valid ring (i.e. a degnerate ring of 3 or fewer points). In
  * this case a LineString is returned. Subclasses may wish to override this method and check for
  * this situation (e.g. a subclass may choose to eliminate degenerate linear rings)
  *
  * @param geom the ring to simplify
  * @param parent the parent geometry
  * @return a LinearRing if the transformation resulted in a structurally valid ring
  * @return a LineString if the transformation caused the LinearRing to collapse to 3 or fewer
  *     points
  */
 protected Geometry transformLinearRing(LinearRing geom, Geometry parent) {
   CoordinateSequence seq = transformCoordinates(geom.getCoordinateSequence(), geom);
   if (seq == null) return factory.createLinearRing((CoordinateSequence) null);
   int seqSize = seq.size();
   // ensure a valid LinearRing
   if (seqSize > 0 && seqSize < 4 && !preserveType) return factory.createLineString(seq);
   return factory.createLinearRing(seq);
 }
 public static LineString makeLineString(double... coords) {
   GeometryFactory factory = getGeometryFactory();
   Coordinate[] coordinates = new Coordinate[coords.length / 2];
   for (int i = 0; i < coords.length; i += 2) {
     coordinates[i / 2] = new Coordinate(coords[i], coords[i + 1]);
   }
   return factory.createLineString(coordinates);
 }
  private DataStore createLatLonDataStore() throws Exception {
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("latlon");
    tb.add("the_geom", LineString.class, CRS.decode("EPSG:4326", true));
    tb.add("level", Integer.class);

    SimpleFeatureType type = tb.buildFeatureType();
    MemoryDataStore ds = new MemoryDataStore();

    ds.createSchema(type);

    FeatureWriter<SimpleFeatureType, SimpleFeature> writer;
    writer = ds.getFeatureWriterAppend("latlon", Transaction.AUTO_COMMIT);

    for (int lon = -180; lon < 180; lon += 5) {
      for (int lat = -90; lat < 90; lat += 5) {
        LineString geom;
        int level;

        geom =
            gf.createLineString(
                new Coordinate[] {new Coordinate(lon, lat), new Coordinate(lon, lat + 5)});

        level = 1;
        if (lon % 10 == 0) {
          level = 10;
        }
        if (lon % 30 == 0) {
          level = 30;
        }

        SimpleFeature f;
        f = writer.next();
        f.setAttribute(0, geom);
        f.setAttribute(1, Integer.valueOf(level));
        writer.write();

        geom =
            gf.createLineString(
                new Coordinate[] {new Coordinate(lon, lat), new Coordinate(lon + 5, lat)});

        level = 1;
        if (lat % 10 == 0) {
          level = 10;
        }
        if (lat % 30 == 0) {
          level = 30;
        }
        f = writer.next();
        f.setAttribute(0, geom);
        f.setAttribute(1, Integer.valueOf(level));
        writer.write();
      }
    }
    writer.close();

    return ds;
  }
Esempio n. 21
0
 @Test
 public void testProyeccion() {
   GeometryFactory factory = new GeometryFactory();
   final String sourceSRID = "EPSG:4326";
   final String targetSRID = "EPSG:3395";
   Geometry geom = factory.createPoint(new Coordinate(42.349167d, 3.684722d));
   geom = MessageProcessor.transform(geom, sourceSRID, targetSRID);
   assertEquals(geom.toText(), "POINT (410181.3767547725 5184634.982024495)");
 }
 @Test
 public void multiPoint() throws Exception {
   MultiPoint multiPoint =
       gf.createMultiPoint(new Point[] {gf.createPoint(new Coordinate(1.2345678, 2.3456789))});
   assertRoundTrip(multiPoint);
   assertThat(
       toJson(multiPoint),
       equalTo("{\"type\":\"MultiPoint\",\"coordinates\":[[1.2345678,2.3456789]]}"));
 }
Esempio n. 23
0
  Polygon createPolygon(List list) {
    LinearRing shell = gf.createLinearRing(coordseq((List) ensureSize(list, 1).get(0)));
    LinearRing[] holes = list.size() > 1 ? new LinearRing[list.size() - 1] : null;

    for (int i = 1; i < list.size(); i++) {
      holes[i - 1] = gf.createLinearRing(coordseq((List) list.get(i)));
    }
    return gf.createPolygon(shell, holes);
  }
Esempio n. 24
0
  @Test
  public void toEnvelope() {
    Coordinate[] coords = getPolyCoords();
    GeometryFactory gf = new GeometryFactory();
    Geometry geom = gf.createPolygon(gf.createLinearRing(coords), null);

    ReferencedEnvelope refEnv = JTS.toEnvelope(geom);
    assertTrue(geom.getEnvelopeInternal().equals(refEnv));
  }
Esempio n. 25
0
  private static Set<Point> filterCoors(Set<Coord> source, Geometry zone) {
    GeometryFactory factory = new GeometryFactory();
    Set<Point> points = new HashSet<Point>();
    for (Coord c : source) {
      Point p = factory.createPoint(new Coordinate(c.getX(), c.getY()));
      if (zone.contains(p)) points.add(p);
    }

    return points;
  }
Esempio n. 26
0
 protected MultiLineString decodeMultiLineString(JsonNode node, GeometryFactory fac)
     throws GeoJSONException {
   JsonNode coordinates = requireCoordinates(node);
   LineString[] lineStrings = new LineString[coordinates.size()];
   for (int i = 0; i < coordinates.size(); ++i) {
     JsonNode coords = coordinates.get(i);
     lineStrings[i] = fac.createLineString(decodeCoordinates(coords));
   }
   return fac.createMultiLineString(lineStrings);
 }
Esempio n. 27
0
 private static Geometry convertSegStrings(Iterator it) {
   GeometryFactory fact = new GeometryFactory();
   List lines = new ArrayList();
   while (it.hasNext()) {
     SegmentString ss = (SegmentString) it.next();
     LineString line = fact.createLineString(ss.getCoordinates());
     lines.add(line);
   }
   return fact.buildGeometry(lines);
 }
    private static ArrayList<Integer> LocateCurrentZone(
        String Coordinates, String VesselProductType, HashMap<Integer, VesselZone> Zonemap) {
      String[] longlat = Coordinates.split(",");
      GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
      Coordinate coord =
          new Coordinate(Double.parseDouble(longlat[1]), Double.parseDouble(longlat[0]));
      Point point = geometryFactory.createPoint(coord);

      ArrayList<Integer> CurrentZones = new ArrayList<Integer>();

      Integer BelongedGlobalZoneIndex = null;

      for (int i = 0; i < VesselZone.GlobalZones.length; i++) {
        if (VesselZone.GlobalZones[i].covers(point)) {
          BelongedGlobalZoneIndex = i;
          break;
        }
      }

      for (Map.Entry<Integer, VesselZone> thisEntry : Zonemap.entrySet()) {

        VesselZone thisZone = thisEntry.getValue();

        String ZoneType = thisZone.getZoneType();

        if (ZoneType.startsWith("ZONE")) {
          String Classfications = ZoneType.substring(5);

          if (VesselProductType.equals("Tankers")) {
            if (Classfications.indexOf("TANKER") == -1) {
              continue;
            }
          } else if (VesselProductType.equals("Bulkers")) {
            if (Classfications.indexOf("DRY") == -1) {
              continue;
            }
          } else if (VesselProductType.equals("Container / Roro")) {
            if (Classfications.indexOf("LINER") == -1) {
              continue;
            }
          } else if (VesselProductType.equals("Miscellaneous")
              || VesselProductType.equals("Passenger")) {
            continue;
          }
        }

        if (thisZone.IntersectedWithGlobalZone(BelongedGlobalZoneIndex)) {
          if (thisZone.getPolygon().covers(point)) {
            CurrentZones.add(thisZone.getAxsmarine_ID());
          }
        }
      }

      return CurrentZones;
    }
Esempio n. 29
0
  public boolean onToolTouchEvent(MotionEvent event) {
    if (mapView == null || mapView.isClickable()) {
      return false;
    }
    Projection pj = editingViewProjection;

    // handle drawing
    currentX = event.getX();
    currentY = event.getY();

    int action = event.getAction();
    switch (action) {
      case MotionEvent.ACTION_DOWN:
        startGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        pj.toPixels(startGeoPoint, startP);
        endP.set(startP.x, startP.y);

        drawingPath.reset();
        drawingPath.moveTo(startP.x, startP.y);

        lastX = currentX;
        lastY = currentY;
        break;
      case MotionEvent.ACTION_MOVE:
        float dx = currentX - lastX;
        float dy = currentY - lastY;
        if (abs(dx) < 1 && abs(dy) < 1) {
          lastX = currentX;
          lastY = currentY;
          return true;
        }
        GeoPoint currentGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        pj.toPixels(currentGeoPoint, tmpP);
        drawingPath.lineTo(tmpP.x, tmpP.y);
        endP.set(tmpP.x, tmpP.y);

        EditManager.INSTANCE.invalidateEditingView();
        break;
      case MotionEvent.ACTION_UP:
        GeoPoint endGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        GeometryFactory gf = new GeometryFactory();
        Coordinate startCoord =
            new Coordinate(startGeoPoint.getLongitude(), startGeoPoint.getLatitude());
        com.vividsolutions.jts.geom.Point startPoint = gf.createPoint(startCoord);
        Coordinate endCoord = new Coordinate(endGeoPoint.getLongitude(), endGeoPoint.getLatitude());
        com.vividsolutions.jts.geom.Point endPoint = gf.createPoint(endCoord);
        Envelope env = new Envelope(startCoord, endCoord);
        select(env.getMaxY(), env.getMinX(), env.getMinY(), env.getMaxX(), startPoint, endPoint);
        //            EditManager.INSTANCE.invalidateEditingView();
        break;
    }

    return true;
  }
 @Test
 public void geometryCollection() throws Exception {
   GeometryCollection collection =
       gf.createGeometryCollection(
           new Geometry[] {gf.createPoint(new Coordinate(1.2345678, 2.3456789))});
   assertRoundTrip(collection);
   assertThat(
       toJson(collection),
       equalTo(
           "{\"type\":\"GeometryCollection\",\"geometries\":[{\"type\":\"Point\",\"coordinates\":[1.2345678,2.3456789]}]}"));
 }