com.vividsolutions.jts.geom.Polygon Java Examples

The following examples show how to use com.vividsolutions.jts.geom.Polygon. 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: GeometryUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static Geometry buildPolygon(final List<List<ILocation>> listPoints) {
	final List<ILocation> coords = listPoints.get(0);
	final int nb = coords.size();
	final Coordinate[] coordinates = new Coordinate[nb];
	for (int i = 0; i < nb; i++) {
		coordinates[i] = (Coordinate) coords.get(i);
	}
	final int nbHoles = listPoints.size() - 1;
	LinearRing[] holes = null;
	if (nbHoles > 0) {
		holes = new LinearRing[nbHoles];
		for (int i = 0; i < nbHoles; i++) {
			final List<ILocation> coordsH = listPoints.get(i + 1);
			final int nbp = coordsH.size();
			final Coordinate[] coordinatesH = new Coordinate[nbp];
			for (int j = 0; j < nbp; j++) {
				coordinatesH[j] = (Coordinate) coordsH.get(j);
			}
			holes[i] = GEOMETRY_FACTORY.createLinearRing(coordinatesH);
		}
	}
	final Polygon poly = GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), holes);
	return poly;
}
 
Example #2
Source File: AbstractTestObsStorage.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
protected void testFilterFoiByRoi(Bbox bbox, int... foiNums)
{
    final Polygon poly = (Polygon)new GeometryFactory().toGeometry(bbox.toJtsEnvelope());
    FoiFilter filter = new FoiFilter()
    {
        public Polygon getRoi() { return poly; };
        public Collection<String> getProducerIDs() {return producerFilterList; };
    };
    
    // test retrieve objects
    Iterator<AbstractFeature> it = storage.getFois(filter);
    int i = 0;
    while (it.hasNext())
        assertEquals(FOI_UID_PREFIX + foiNums[i++], it.next().getUniqueIdentifier());
    assertEquals(foiNums.length, i);
    
    // test retrieve ids only
    Iterator<String> it2 = storage.getFoiIDs(filter);
    i = 0;
    while (it2.hasNext())
        assertEquals(FOI_UID_PREFIX + foiNums[i++], it2.next());
    assertEquals(foiNums.length, i);
}
 
Example #3
Source File: WKTWriterTest.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testWriteMultiPolygon() throws Exception {
    Coordinate[] coordinates1 = { new Coordinate(10, 10, 0),
                                 new Coordinate(10, 20, 0),
                                 new Coordinate(20, 20, 0),
                                 new Coordinate(20, 15, 0),
                                 new Coordinate(10, 10, 0) };
    LinearRing linearRing1 = geometryFactory.createLinearRing(coordinates1);
    Polygon polygon1 = geometryFactory.createPolygon(linearRing1, new LinearRing[] { });
    Coordinate[] coordinates2 = { new Coordinate(60, 60, 0),
                                 new Coordinate(70, 70, 0),
                                 new Coordinate(80, 60, 0),
                                 new Coordinate(60, 60, 0) };
    LinearRing linearRing2 = geometryFactory.createLinearRing(coordinates2);
    Polygon polygon2 = geometryFactory.createPolygon(linearRing2, new LinearRing[] { });
    Polygon[] polygons = {polygon1, polygon2};
    MultiPolygon multiPolygon = geometryFactory.createMultiPolygon(polygons);
//    System.out.println("MULTIPOLYGON (((10 10, 10 20, 20 20, 20 15, 10 10)), ((60 60, 70 70, 80 60, 60 60)))");
//    System.out.println(writer.write(multiPolygon).toString());
    assertEquals("MULTIPOLYGON (((10 10, 10 20, 20 20, 20 15, 10 10)), ((60 60, 70 70, 80 60, 60 60)))", writer.write(multiPolygon).toString());
  }
 
Example #4
Source File: JTSModel.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addOSMClosedWays(OSMDataSet ds) {
    List<OSMWay> closedWays = ds.getClosedWays();
    for (OSMWay w : closedWays) {
        if (!w.isModified() && OSMWay.containsModifiedWay(w.getId())) {
            continue;    
        }
        // Don't render or index ways that do not have all of their referenced nodes.
        if (w.incomplete()) {
            continue;
        }
        List<OSMNode> nodes = w.getNodes();
        Coordinate[] coords = coordArrayFromNodeList(nodes);
        Polygon poly = geometryFactory.createPolygon(coords);
        w.setJTSGeom(poly);
        Envelope envelope = poly.getEnvelopeInternal();
        spatialIndex.insert(envelope, w);
    }
}
 
Example #5
Source File: GeometryConverterTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private com.vividsolutions.jts.geom.Geometry createJtsEmpty(Class<?> clazz) {
	if (Point.class.equals(clazz)) {
		return factory.createPoint((com.vividsolutions.jts.geom.Coordinate) null);
	} else if (LineString.class.equals(clazz)) {
		return factory.createLineString((com.vividsolutions.jts.geom.Coordinate[]) null);
	} else if (LinearRing.class.equals(clazz)) {
		return factory.createLinearRing((com.vividsolutions.jts.geom.Coordinate[]) null);
	} else if (Polygon.class.equals(clazz)) {
		return factory.createPolygon(null, null);
	} else if (MultiPoint.class.equals(clazz)) {
		return factory.createMultiPoint((Point[]) null);
	} else if (MultiLineString.class.equals(clazz)) {
		return factory.createMultiLineString((LineString[]) null);
	} else if (MultiPolygon.class.equals(clazz)) {
		return factory.createMultiPolygon((Polygon[]) null);
	} else {
		return null;
	}
}
 
Example #6
Source File: SearchByLocationCommandTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void intersect50percentOverlapAlmost() throws Exception {
	// prepare command
	SearchByLocationRequest request = new SearchByLocationRequest();
	request.setCrs("EPSG:4326");
	request.setQueryType(SearchByLocationRequest.QUERY_INTERSECTS);
	request.setSearchType(SearchByLocationRequest.SEARCH_ALL_LAYERS);
	request.setRatio(0.5f);
	request.setLayerIds(new String[] {LAYER_ID});

	// create a rectangle that overlaps 49 %
	GeometryFactory factory = new GeometryFactory();
	LinearRing half1 = factory.createLinearRing(new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 0),
			new Coordinate(1, 0.49), new Coordinate(0, 0.49), new Coordinate(0, 0)});
	Polygon polygon = factory.createPolygon(half1, null);
	request.setLocation(converter.toDto(polygon));

	// execute
	SearchByLocationResponse response = (SearchByLocationResponse) dispatcher.execute(
			SearchByLocationRequest.COMMAND, request, null, "en");
	// test
	List<Feature> features = response.getFeatureMap().get(LAYER_ID);
	Assert.assertNull(features);
}
 
Example #7
Source File: FilterServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testIntersectsFilter() throws GeomajasException, ParseException {
	Polygon poly1 = (Polygon) wkt.read("POLYGON((0 0,1 0,1 1,0 1,0 0))");
	Polygon touching = (Polygon) wkt.read("POLYGON((1 1,2 1,2 2,1 2,1 1))");
	Polygon disjoint = (Polygon) wkt.read("POLYGON((2 2,3 2,3 3,2 3,2 2))");
	Polygon overlapping = (Polygon) wkt.read("POLYGON((0.5 0.5,1.5 0.5,1.5 1.5,0.5 1.5,0.5 0.5))");
	Polygon within = (Polygon) wkt.read("POLYGON((0.1 0.1,0.9 0.1,0.9 0.9,0.1 0.9,0.1 0.1))");
	Polygon contains = (Polygon) wkt.read("POLYGON((-0.1 -0.1,1.1 -0.1,1.1 1.1,-0.1 1.1,-0.1 -0.1))");
	Filter filter = filterService.createIntersectsFilter(poly1, "geometry");
	TestFeature f = new TestFeature();
	f.expectAndReturn("geometry", touching);
	Assert.assertTrue(filter.evaluate(f));
	f.clear();
	f.expectAndReturn("geometry", disjoint);
	Assert.assertFalse(filter.evaluate(f));
	f.clear();
	f.expectAndReturn("geometry", overlapping);
	Assert.assertTrue(filter.evaluate(f));
	f.clear();
	f.expectAndReturn("geometry", within);
	Assert.assertTrue(filter.evaluate(f));
	f.clear();
	f.expectAndReturn("geometry", contains);
	Assert.assertTrue(filter.evaluate(f));
}
 
Example #8
Source File: WKTWriter.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *  Converts a <code>MultiPolygon</code> to &lt;MultiPolygon Text&gt; format,
 *  then appends it to the writer.
 *
 *@param  multiPolygon  the <code>MultiPolygon</code> to process
 *@param  writer        the output writer to append to
 */
private void appendMultiPolygonText(MultiPolygon multiPolygon, int level, Writer writer)
  throws IOException
{
  if (multiPolygon.isEmpty()) {
    writer.write("EMPTY");
  }
  else {
    int level2 = level;
    boolean doIndent = false;
    writer.write("(");
    for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
      if (i > 0) {
        writer.write(", ");
        level2 = level + 1;
        doIndent = true;
      }
      appendPolygonText((Polygon) multiPolygon.getGeometryN(i), level2, doIndent, writer);
    }
    writer.write(")");
  }
}
 
Example #9
Source File: Distance3DOp.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void computeMinDistanceOneMulti(PlanarPolygon3D poly, Geometry geom, boolean flip) {
	if (geom instanceof GeometryCollection) {
		int n = geom.getNumGeometries();
		for (int i = 0; i < n; i++) {
			Geometry g = geom.getGeometryN(i);
			computeMinDistanceOneMulti(poly, g, flip);
			if (isDone)	return;
		}
	}
	else {
		if (geom instanceof Point) {
			computeMinDistancePolygonPoint(poly, (Point) geom, flip);
			return;
		}
		if (geom instanceof LineString) {
			computeMinDistancePolygonLine(poly, (LineString) geom, flip);
			return;
		}
		if (geom instanceof Polygon) {
			computeMinDistancePolygonPolygon(poly, (Polygon) geom, flip);
			return;
		}
	}
}
 
Example #10
Source File: WKBWriter.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Writes a {@link Geometry} to an {@link OutStream}.
 *
 * @param geom the geometry to write
 * @param os the out stream to write to
 * @throws IOException if an I/O error occurs
 */
public void write(Geometry geom, OutStream os) throws IOException
{
  if (geom instanceof Point)
    writePoint((Point) geom, os);
  // LinearRings will be written as LineStrings
  else if (geom instanceof LineString)
    writeLineString((LineString) geom, os);
  else if (geom instanceof Polygon)
    writePolygon((Polygon) geom, os);
  else if (geom instanceof MultiPoint)
    writeGeometryCollection(WKBConstants.wkbMultiPoint, 
        (MultiPoint) geom, os);
  else if (geom instanceof MultiLineString)
    writeGeometryCollection(WKBConstants.wkbMultiLineString,
        (MultiLineString) geom, os);
  else if (geom instanceof MultiPolygon)
    writeGeometryCollection(WKBConstants.wkbMultiPolygon,
        (MultiPolygon) geom, os);
  else if (geom instanceof GeometryCollection)
    writeGeometryCollection(WKBConstants.wkbGeometryCollection,
        (GeometryCollection) geom, os);
  else {
    Assert.shouldNeverReachHere("Unknown Geometry type");
  }
}
 
Example #11
Source File: GeospatialTest.java    From fiware-cepheus with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testGeometryMethod() {
    epService.getEPAdministrator().createEPL("create variable Geometry geoVar = geometry(\"POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))\")");
    Object value = epService.getEPRuntime().getVariableValue("geoVar");
    assertNotNull(value);
    assertThat(value, instanceOf(Polygon.class));

    Polygon poly = (Polygon)value;
    assertEquals(20, poly.getCoordinates()[0].getOrdinate(Coordinate.X), 0.001);
    assertEquals(10, poly.getCoordinates()[0].getOrdinate(Coordinate.Y), 0.001);
    assertEquals(30, poly.getCoordinates()[1].getOrdinate(Coordinate.X), 0.001);
    assertEquals(0, poly.getCoordinates()[1].getOrdinate(Coordinate.Y), 0.001);
    assertEquals(40, poly.getCoordinates()[2].getOrdinate(Coordinate.X), 0.001);
    assertEquals(10, poly.getCoordinates()[2].getOrdinate(Coordinate.Y), 0.001);
    assertEquals(30, poly.getCoordinates()[3].getOrdinate(Coordinate.X), 0.001);
    assertEquals(20, poly.getCoordinates()[3].getOrdinate(Coordinate.Y), 0.001);
    assertEquals(20, poly.getCoordinates()[4].getOrdinate(Coordinate.X), 0.001);
    assertEquals(10, poly.getCoordinates()[4].getOrdinate(Coordinate.Y), 0.001);
}
 
Example #12
Source File: AllowedAttributeTypes.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialise.
 */
private static void initialise()
{
    List<Class<?> > doubleList = new ArrayList<Class<?> >(Arrays.asList(Integer.class, Long.class, Double.class, Float.class));
    List<Class<?> > integerList = new ArrayList<Class<?> >(Arrays.asList(Integer.class, Long.class));
    List<Class<?> > stringList = new ArrayList<Class<?> >(Arrays.asList(String.class));
    List<Class<?> > geometryList = new ArrayList<Class<?> >(Arrays.asList(Point.class, LineString.class, Polygon.class, MultiPolygon.class, MultiPoint.class, MultiLineString.class));

    allowedClassTypeMap.put(String.class, stringList);
    allowedClassTypeMap.put(Double.class, doubleList);
    allowedClassTypeMap.put(Float.class, doubleList);
    allowedClassTypeMap.put(Integer.class, integerList);
    allowedClassTypeMap.put(Long.class, integerList);
    allowedClassTypeMap.put(Geometry.class, geometryList);

    List<Class<?> > objectList = new ArrayList<Class<?>>();
    objectList.addAll(doubleList);
    objectList.addAll(integerList);
    objectList.addAll(stringList);
    objectList.addAll(geometryList);
    allowedClassTypeMap.put(Object.class, objectList);
}
 
Example #13
Source File: GeometryDrawer.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private void drawPolygon(final Polygon p, final boolean solid, final Color border, final boolean clockwise,
		final boolean computeVertices) {
	if (computeVertices) {
		_vertices.setToYNegated(getContourCoordinates(p));
	}
	if (solid) {
		gl.setNormal(_vertices, clockwise);
		final boolean hasHoles = getHolesNumber(p) > 0;
		final int size = _vertices.size();
		if (hasHoles || size > 5) {
			gl.drawPolygon(p, _vertices, clockwise);
		} else {
			gl.drawSimpleShape(_vertices, size - 1, solid, clockwise, false, null);
		}
	}
	if (border != null) {
		gl.drawClosedLine(_vertices, border, -1);
		applyToInnerGeometries(p, ring -> gl.drawClosedLine(getYNegatedCoordinates(ring), border, -1));
	}
}
 
Example #14
Source File: KMLWriter.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void writeGeometry(Geometry g, int level, StringBuffer buf) {
  String attributes = "";
  if (g instanceof Point) {
    writePoint((Point) g, attributes, level, buf);
  } else if (g instanceof LinearRing) {
    writeLinearRing((LinearRing) g, attributes, true, level, buf);
  } else if (g instanceof LineString) {
    writeLineString((LineString) g, attributes, level, buf);
  } else if (g instanceof Polygon) {
    writePolygon((Polygon) g, attributes, level, buf);
  } else if (g instanceof GeometryCollection) {
    writeGeometryCollection((GeometryCollection) g, attributes, level, buf);
  }
  else 
    throw new IllegalArgumentException("Geometry type not supported: " + g.getGeometryType());
}
 
Example #15
Source File: PolygonOverlayFunctions.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Geometry overlaySnapRounded(Geometry g1, Geometry g2, double precisionTol)
{
  PrecisionModel pm = new PrecisionModel(precisionTol);
  GeometryFactory geomFact = g1.getFactory();
  
  List lines = LinearComponentExtracter.getLines(g1);
  // add second input's linework, if any
  if (g2 != null)
    LinearComponentExtracter.getLines(g2, lines);
  List nodedLinework = new GeometryNoder(pm).node(lines);
  // union the noded linework to remove duplicates
  Geometry nodedDedupedLinework = geomFact.buildGeometry(nodedLinework).union();
  
  // polygonize the result
  Polygonizer polygonizer = new Polygonizer();
  polygonizer.add(nodedDedupedLinework);
  Collection polys = polygonizer.getPolygons();
  
  // convert to collection for return
  Polygon[] polyArray = GeometryFactory.toPolygonArray(polys);
  return geomFact.createGeometryCollection(polyArray);
}
 
Example #16
Source File: KMLWriter.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void writePolygon(Polygon p, String attributes, int level,
    StringBuffer buf) {
  startLine(geometryTag("Polygon", attributes) + "\n", level, buf);
  writeModifiers(level, buf);

  startLine("  <outerBoundaryIs>\n", level, buf);
  writeLinearRing((LinearRing) p.getExteriorRing(), null, false, level + 1, buf);
  startLine("  </outerBoundaryIs>\n", level, buf);

  for (int t = 0; t < p.getNumInteriorRing(); t++) {
    startLine("  <innerBoundaryIs>\n", level, buf);
    writeLinearRing((LinearRing) p.getInteriorRingN(t), null, false, level + 1, buf);
    startLine("  </innerBoundaryIs>\n", level, buf);
  }

  startLine("</Polygon>\n", level, buf);
}
 
Example #17
Source File: MultiPolygonWriter.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #18
Source File: SameStructureTester.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isSameStructure(Geometry g1, Geometry g2)
{
  if (g1.getClass() != g2.getClass())
    return false;
  if (g1 instanceof GeometryCollection)
    return isSameStructureCollection((GeometryCollection) g1, (GeometryCollection) g2);
  else if (g1 instanceof Polygon)
    return isSameStructurePolygon((Polygon) g1, (Polygon) g2);
  else if (g1 instanceof LineString)
    return isSameStructureLineString((LineString) g1, (LineString) g2);
  else if (g1 instanceof Point)
    return isSameStructurePoint((Point) g1, (Point) g2);

  Assert.shouldNeverReachHere(
      "Unsupported Geometry class: " + g1.getClass().getName());
  return false;
}
 
Example #19
Source File: WKTWriter.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *  Converts a <code>Polygon</code> to &lt;Polygon Text&gt; format, then
 *  appends it to the writer.
 *
 *@param  polygon  the <code>Polygon</code> to process
 *@param  writer   the output writer to append to
 */
private void appendPolygonText(Polygon polygon, int level, boolean indentFirst, Writer writer)
  throws IOException
{
  if (polygon.isEmpty()) {
    writer.write("EMPTY");
  }
  else {
    if (indentFirst) indent(level, writer);
    writer.write("(");
    appendLineStringText(polygon.getExteriorRing(), level, false, writer);
    for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
      writer.write(", ");
      appendLineStringText(polygon.getInteriorRingN(i), level + 1, true, writer);
    }
    writer.write(")");
  }
}
 
Example #20
Source File: GeometryUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static Geometry cleanGeometry(final Geometry g) {
	//follow the proposition of https://locationtech.github.io/jts/jts-faq.html#G1
	if (g == null || g.isEmpty()) return g; 
	Geometry g2 = g.buffer(0.0, BufferParameters.DEFAULT_QUADRANT_SEGMENTS,
			BufferParameters.CAP_FLAT);
	if (g2.isEmpty()) {
		if (g instanceof Polygon) {
			Polygon p = (Polygon) g;
			Geometry g3 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getExteriorRing().getCoordinates());
			for (int i = 0; i < p.getNumInteriorRing(); i++) {
				Geometry g4 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getInteriorRingN(i).getCoordinates());
				g3 = g3.difference(g4);
			}
			return g3;
		}else {
			return GeometryUtils.GEOMETRY_FACTORY.createGeometry(g);
		}
	}
	return g2;
}
 
Example #21
Source File: GamaGeometryType.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static IShape buildTriangle(final double base, final double height, final ILocation location) {
	final Coordinate[] points = new Coordinate[4];
	final double z = location == null ? 0.0 : location.getZ();
	points[0] = new GamaPoint(-base / 2.0, height / 2, z);
	points[1] = new GamaPoint(0, -height / 2, z);
	points[2] = new GamaPoint(base / 2.0, height / 2, z);
	points[3] = points[0];
	final CoordinateSequenceFactory fact = GamaGeometryFactory.COORDINATES_FACTORY;
	final CoordinateSequence cs = fact.create(points);
	final LinearRing geom = GeometryUtils.GEOMETRY_FACTORY.createLinearRing(cs);
	final Polygon p = GeometryUtils.GEOMETRY_FACTORY.createPolygon(geom, null);
	final IShape s = new GamaShape(p);
	if (location != null) {
		s.setLocation(location);
	}
	return s;
}
 
Example #22
Source File: SaveStatement.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static String getGeometryType(final List<? extends IShape> agents) {
	String geomType = "";
	for (final IShape be : agents) {
		final IShape geom = be.getGeometry();
		if (geom != null && geom.getInnerGeometry() != null) {
			geomType = geom.getInnerGeometry().getClass().getSimpleName();
			if (geom.getInnerGeometry().getNumGeometries() > 1) {
				if (geom.getInnerGeometry().getGeometryN(0).getClass() == Point.class) {
					geomType = MultiPoint.class.getSimpleName();
				} else if (geom.getInnerGeometry().getGeometryN(0).getClass() == LineString.class) {
					geomType = MultiLineString.class.getSimpleName();
				} else if (geom.getInnerGeometry().getGeometryN(0).getClass() == Polygon.class) {
					geomType = MultiPolygon.class.getSimpleName();
				}
				break;
			}
		}
	}
	if ("DynamicLineString".equals(geomType)) {
		geomType = LineString.class.getSimpleName();
	}
	return geomType;
}
 
Example #23
Source File: OraReader.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Create MultiPolygon as encoded by elemInfo.
 *
 * @param oraGeom SDO_GEOMETRY attributes being read
 * @param coords the coordinates of the entire geometry
 * @return MultiPolygon
 */
private MultiPolygon readMultiPolygon(OraGeom oraGeom)
{
  int nElem = oraGeom.numElements();
  List geoms = new ArrayList();
  for (int i = 0; i < nElem; i++) {
    int etype = oraGeom.eType(i);
    if ((etype == OraGeom.ETYPE.POLYGON) || (etype == OraGeom.ETYPE.POLYGON_EXTERIOR)) {
      Polygon poly = readPolygon(oraGeom, i);
      i += poly.getNumInteriorRing(); // skip interior rings
      geoms.add(poly);
    } 
    else { // not a Polygon - stop reading
    	break;
    }
  }
  MultiPolygon polys = geometryFactory.createMultiPolygon(GeometryFactory.toPolygonArray(geoms));
  return polys;
}
 
Example #24
Source File: LayerTypeConverterTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testConversion() {
	// dto -> internal
	for (LayerType layerType : LayerType.values()) {
		if (layerType != LayerType.RASTER) {
			Class<? extends Geometry> c = converterService.toInternal(layerType);
			Assert.assertEquals(layerType.name(), c.getSimpleName().toUpperCase());
		} else {
			Assert.assertNull(converterService.toInternal(layerType));
		}
	}
	// internal -> dto
	Assert.assertEquals(LayerType.POINT, converterService.toDto(Point.class));
	Assert.assertEquals(LayerType.MULTIPOINT, converterService.toDto(MultiPoint.class));
	Assert.assertEquals(LayerType.LINESTRING, converterService.toDto(LineString.class));
	Assert.assertEquals(LayerType.MULTILINESTRING, converterService.toDto(MultiLineString.class));
	Assert.assertEquals(LayerType.POLYGON, converterService.toDto(Polygon.class));
	Assert.assertEquals(LayerType.MULTIPOLYGON, converterService.toDto(MultiPolygon.class));
	Assert.assertEquals(LayerType.GEOMETRY, converterService.toDto(Geometry.class));
}
 
Example #25
Source File: GeometryDrawer.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private void drawPolyhedron(final Polygon polygon, final boolean solid, final double height, final Color border) {
	final boolean hasHoles = getHolesNumber(polygon) > 0;
	// Draw bottom
	drawPolygon(polygon, solid, hasHoles ? border : null, true, true);
	_vertices.getNormal(true, height, _normal);
	try {
		gl.pushMatrix();
		gl.translateBy(_normal.x, _normal.y, _normal.z);
		// Draw top
		drawPolygon(polygon, solid, hasHoles ? border : null, true, false);
	} finally {
		gl.popMatrix();
	}
	gl.enableAlternateTexture();
	// Draw faces
	_vertices.visit((pj, pk) -> {
		_quadvertices.setTo(pk.x, pk.y, pk.z, pk.x + _normal.x, pk.y + _normal.y, pk.z + _normal.z,
				pj.x + _normal.x, pj.y + _normal.y, pj.z + _normal.z, pj.x, pj.y, pj.z, pk.x, pk.y, pk.z);
		gl.drawSimpleShape(_quadvertices, 4, solid, true, true, border);
	});

}
 
Example #26
Source File: BufferValidator.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BufferValidator setBufferHolesExpected(final boolean bufferHolesExpected) {
  return addTest(new Test("Buffer Holes Test") {
    public void test() throws Exception {
      Assert.assertTrue(
        supplement(
          "Expected buffer "
            + (bufferHolesExpected ? "" : "not ")
            + "to have holes"),
        hasHoles(getBuffer()) == bufferHolesExpected);
    }
    private boolean hasHoles(Geometry buffer) {
      if (buffer.isEmpty()) {
        return false;
      }
      if (buffer instanceof Polygon) {
        return ((Polygon) buffer).getNumInteriorRing() > 0;
      }
      MultiPolygon multiPolygon = (MultiPolygon) buffer;
      for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
        if (hasHoles(multiPolygon.getGeometryN(i))) {
          return true;
        }
      }
      return false;
    }
  });
}
 
Example #27
Source File: MiscellaneousTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testPolygonGetCoordinates() throws Exception {
  Polygon p = (Polygon) reader.read(
        "POLYGON ( (0 0, 100 0, 100 100, 0 100, 0 0), "
      + "          (20 20, 20 80, 80 80, 80 20, 20 20)) ");
  Coordinate[] coordinates = p.getCoordinates();
  assertEquals(10, p.getNumPoints());
  assertEquals(10, coordinates.length);
  assertEquals(new Coordinate(0, 0), coordinates[0]);
  assertEquals(new Coordinate(20, 20), coordinates[9]);
}
 
Example #28
Source File: GeoWaveIndexerSfTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * convert a Polygon geometry to GML
 * @param geometry
 * @return String that is XML that is a GMLLiteral of line
 */
private static String geoToGml(final Polygon poly) {
    final StringBuilder coordString = new StringBuilder() ;
    for (final Coordinate coor : poly.getCoordinates()) {
        coordString.append(" ").append(coor.x).append(" ").append(coor.y); //ESPG:4326 lat/long
        //with commas:  coordString.append(" ").append(coor.x).append(",").append(coor.y);
    }
    return "<gml:Polygon srsName=\"EPSG:4326\"  xmlns:gml='http://www.opengis.net/gml'>\r\n"//
            + "<gml:exterior><gml:LinearRing>\r\n"//
            + "<gml:posList srsDimension='2'>\r\n"
            +  coordString
            + "</gml:posList>\r\n"//
            + "</gml:LinearRing></gml:exterior>\r\n</gml:Polygon>\r\n";
}
 
Example #29
Source File: SearchByLocationCommandTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void intersect50percentOverlapExactly() throws Exception {
	// prepare command
	SearchByLocationRequest request = new SearchByLocationRequest();
	request.setCrs("EPSG:4326");
	request.setQueryType(SearchByLocationRequest.QUERY_INTERSECTS);
	request.setSearchType(SearchByLocationRequest.SEARCH_ALL_LAYERS);
	request.setRatio(0.5f);
	request.setLayerIds(new String[] {LAYER_ID});

	// create a rectangle that overlaps 50 %
	GeometryFactory factory = new GeometryFactory();
	LinearRing half1 = factory.createLinearRing(new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 0),
			new Coordinate(1, 0.5), new Coordinate(0, 0.5), new Coordinate(0, 0)});
	Polygon polygon = factory.createPolygon(half1, null);
	request.setLocation(converter.toDto(polygon));

	// execute
	SearchByLocationResponse response = (SearchByLocationResponse) dispatcher.execute(
			SearchByLocationRequest.COMMAND, request, null, "en");

	// test
	Assert.assertFalse(response.isError());
	List<Feature> features = response.getFeatureMap().get(LAYER_ID);
	Assert.assertNotNull(features);
	List<String> actual = new ArrayList<String>();
	for (Feature feature : features) {
		actual.add(feature.getLabel());
	}
	List<String> expected = new ArrayList<String>();
	expected.add("Country 1");
	Assert.assertEquals(expected, actual);
}
 
Example #30
Source File: GeoIndexerSfTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * convert a Polygon geometry to GML
 * @param geometry
 * @return String that is XML that is a GMLLiteral of line
 */
private static String geoToGml(final Polygon poly) {
    final StringBuilder coordString = new StringBuilder() ;
    for (final Coordinate coor : poly.getCoordinates()) {
        coordString.append(" ").append(coor.x).append(" ").append(coor.y); //ESPG:4326 lat/long
        //with commas:  coordString.append(" ").append(coor.x).append(",").append(coor.y);
    }
    return "<gml:Polygon srsName=\"EPSG:4326\"  xmlns:gml='http://www.opengis.net/gml'>\r\n"//
            + "<gml:exterior><gml:LinearRing>\r\n"//
            + "<gml:posList srsDimension='2'>\r\n"
            +  coordString
            + "</gml:posList>\r\n"//
            + "</gml:LinearRing></gml:exterior>\r\n</gml:Polygon>\r\n";
}