Java Examples for com.vividsolutions.jts.geom.Geometry
The following java examples will help you to understand the usage of com.vividsolutions.jts.geom.Geometry. These source code samples are taken from different open source projects.
Example 1
Project: geogson-master File: JtsGeometryCollectionIterable.java View source code |
public static JtsGeometryCollectionIterable of(final GeometryCollection src) {
return new JtsGeometryCollectionIterable(new GeometryProvider() {
@Override
public int getNumGeometries() {
return src.getNumGeometries();
}
@Override
public Geometry getGeometryN(int n) {
return src.getGeometryN(n);
}
});
}
Example 2
Project: geotools-2.7.x-master File: ParamField.java View source code |
/**
* Factory method creating the appropriate ParamField for the supplied Param.
*
* @param param
* @return
*/
public static ParamField create(Parameter<?> parameter) {
if (Double.class.isAssignableFrom(parameter.type)) {
return new JDoubleField(parameter);
} else if (URL.class.isAssignableFrom(parameter.type)) {
if (parameter.metadata != null && parameter.metadata.get(Parameter.EXT) != null) {
return new JURLField(parameter);
} else {
JField field = new JField(parameter);
field.setSingleLine(true);
return field;
}
} else if (Boolean.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parameter);
field.setSingleLine(true);
return field;
} else if (Number.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parameter);
field.setSingleLine(true);
return field;
} else if (File.class.isAssignableFrom(parameter.type)) {
return new JFileField(parameter);
} else if (Geometry.class.isAssignableFrom(parameter.type)) {
return new JGeometryField(parameter);
} else {
// We got nothing special hope the converter api can deal
return new JField(parameter);
}
}
Example 3
Project: geotools-master File: WFSDiff.java View source code |
public ReferencedEnvelope batchModify(Name[] properties, Object[] values, Filter filter, FeatureReader<SimpleFeatureType, SimpleFeature> oldFeatures, ContentState contentState) throws IOException { ReferencedEnvelope bounds = new ReferencedEnvelope(contentState.getFeatureType().getCoordinateReferenceSystem()); synchronized (batchModified) { while (oldFeatures.hasNext()) { SimpleFeature old = oldFeatures.next(); BoundingBox fbounds = old.getBounds(); if (fbounds != null) { bounds.expandToInclude(new ReferencedEnvelope(fbounds)); } for (int i = 0; i < properties.length; i++) { Name propName = properties[i]; Object newValue = values[i]; old.setAttribute(propName, newValue); if (newValue instanceof Geometry) { Envelope envelope = ((Geometry) newValue).getEnvelopeInternal(); bounds.expandToInclude(envelope); } } String fid = old.getID(); super.modify(fid, old); batchModified.add(fid); } BatchUpdate batch = new BatchUpdate(properties, values, filter); batchCommands.add(batch); } return bounds; }
Example 4
Project: geotools-old-master File: ParamField.java View source code |
/**
* Factory method creating the appropriate ParamField for the supplied Param.
*
* @param param
* @return
*/
public static ParamField create(Composite parent, Parameter<?> parameter) {
if (Double.class.isAssignableFrom(parameter.type)) {
return new JDoubleField(parent, parameter);
} else if (URL.class.isAssignableFrom(parameter.type)) {
if (parameter.metadata != null && parameter.metadata.get(Parameter.EXT) != null) {
return new JURLField(parent, parameter);
} else {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
}
} else if (Boolean.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
} else if (Number.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
} else if (File.class.isAssignableFrom(parameter.type)) {
return new JFileField(parent, parameter);
} else if (Geometry.class.isAssignableFrom(parameter.type)) {
return new JGeometryField(parent, parameter);
} else {
// We got nothing special hope the converter api can deal
return new JField(parent, parameter);
}
}
Example 5
Project: geotools-tike-master File: ProcessRunPage.java View source code |
public void aboutToDisplayPanel() {
page.removeAll();
page.setLayout(new GridLayout(0, 2));
Process process = this.factory.create(name);
final ProgressListener progress = new ProgressWindow(this.getJProcessWizard());
Map<String, Object> resultMap;
try {
resultMap = process.execute(paramMap, progress);
} catch (ProcessException ex) {
Logger.getLogger(ProcessRunPage.class.getName()).log(Level.SEVERE, "Error preparing panel", ex);
return;
}
// when we get here, the processing is over so show the result
JLabel title = new JLabel(factory.getTitle(name).toString());
page.add(title);
JLabel description = new JLabel("Your process results are below:");
page.add(description);
for (Entry<String, Object> entry : resultMap.entrySet()) {
Parameter<?> parameter = new Parameter(entry.getKey(), entry.getValue().getClass(), Text.text("Result"), Text.text("Result of process"));
JLabel label = new JLabel(entry.getKey());
page.add(label);
ParamWidget widget;
if (Double.class.isAssignableFrom(parameter.type)) {
widget = new JDoubleField(parameter);
} else if (Geometry.class.isAssignableFrom(parameter.type)) {
widget = new JGeometryField(parameter);
} else {
// We got nothing special, let's hope the converter api can deal
widget = new JField(parameter);
}
JComponent field = widget.doLayout();
widget.setValue(entry.getValue());
page.add(field);
}
}
Example 6
Project: geotools_trunk-master File: ParamField.java View source code |
/**
* Factory method creating the appropriate ParamField for the supplied Param.
*
* @param param
* @return
*/
public static ParamField create(Composite parent, Parameter<?> parameter) {
if (Double.class.isAssignableFrom(parameter.type)) {
return new JDoubleField(parent, parameter);
} else if (URL.class.isAssignableFrom(parameter.type)) {
if (parameter.metadata != null && parameter.metadata.get(Parameter.EXT) != null) {
return new JURLField(parent, parameter);
} else {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
}
} else if (Boolean.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
} else if (Number.class.isAssignableFrom(parameter.type)) {
JField field = new JField(parent, parameter);
field.setSingleLine(true);
return field;
} else if (File.class.isAssignableFrom(parameter.type)) {
return new JFileField(parent, parameter);
} else if (Geometry.class.isAssignableFrom(parameter.type)) {
return new JGeometryField(parent, parameter);
} else {
// We got nothing special hope the converter api can deal
return new JField(parent, parameter);
}
}
Example 7
Project: geotoolkit-master File: PolygonHandlerTest.java View source code |
public static Geometry copyTo(final double x, final double y, final double w, final double h, final Geometry g) { if (g.getNumPoints() != 5) throw new IllegalArgumentException("Geometry must have 5 points"); if (!LinearRing.class.isAssignableFrom(g.getClass())) throw new IllegalArgumentException("Geometry must be linear ring"); Coordinate[] coords = g.getCoordinates(); coords[0].x = x; coords[0].y = y; coords[1].x = x + w; coords[1].y = y; coords[2].x = x + w; coords[2].y = y + h; coords[3].x = x; coords[3].y = y + h; coords[4].x = x; coords[4].y = y; return g; }
Example 8
Project: geoserver-master File: SVGMapProducerTest.java View source code |
@Test
public void testHeterogeneousGeometry() throws Exception {
GeometryFactory gf = new GeometryFactory();
Point point = gf.createPoint(new Coordinate(10, 10));
LineString line = gf.createLineString(new Coordinate[] { new Coordinate(50, 50), new Coordinate(100, 100) });
Polygon polygon = gf.createPolygon(gf.createLinearRing(new Coordinate[] { new Coordinate(0, 0), new Coordinate(0, 200), new Coordinate(200, 200), new Coordinate(200, 0), new Coordinate(0, 0) }), null);
SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
ftb.setName("test");
ftb.add("geom", Geometry.class);
SimpleFeatureType type = ftb.buildFeatureType();
SimpleFeature f1 = SimpleFeatureBuilder.build(type, new Object[] { point }, null);
SimpleFeature f2 = SimpleFeatureBuilder.build(type, new Object[] { line }, null);
SimpleFeature f3 = SimpleFeatureBuilder.build(type, new Object[] { polygon }, null);
MemoryDataStore ds = new MemoryDataStore();
ds.createSchema(type);
ds.addFeatures(new SimpleFeature[] { f1, f2, f3 });
FeatureSource fs = ds.getFeatureSource("test");
final WMSMapContent map = new WMSMapContent();
map.getViewport().setBounds(new ReferencedEnvelope(-250, 250, -250, 250, null));
map.setMapWidth(300);
map.setMapHeight(300);
map.setBgColor(Color.red);
map.setTransparent(false);
Style basicStyle = getCatalog().getStyleByName("Default").getStyle();
map.addLayer(new FeatureLayer(fs, basicStyle));
SVGStreamingMapOutputFormat producer = new SVGStreamingMapOutputFormat();
StreamingSVGMap encodeSVG = producer.produceMap(map);
ByteArrayOutputStream out = new ByteArrayOutputStream();
encodeSVG.encode(out);
// System.out.println(out.toString());
String expectedDoc = "<?xml version=\"1.0\" standalone=\"no\"?>" + //
"<svg xmlns=\"http://www.w3.org/2000/svg\" " + //
" xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + //
" stroke=\"green\" " + //
" fill=\"none\" " + //
" stroke-width=\"0.1%\" " + //
" stroke-linecap=\"round\" " + //
" stroke-linejoin=\"round\" " + //
" width=\"300\" " + //
" height=\"300\" " + //
" viewBox=\"-250.0 -250.0 500.0 500.0\" " + //
" preserveAspectRatio=\"xMidYMid meet\"> " + //
" <g id=\"test\" class=\"Default\"> " + //
" <use x=\"10\" y=\"-10\" xlink:href=\"#point\"/> " + //
" <path d=\"M50 -50l50 -50 \"/> " + //
" <path d=\"M0 0l0 -200 200 0 0 200 -200 0 Z\"/> " + //
" </g> " + "</svg> ";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document expected = builder.parse(new InputSource(new StringReader(expectedDoc)));
Document result = builder.parse(new ByteArrayInputStream(out.toByteArray()));
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLUnit.setIgnoreComments(true);
XMLAssert.assertXMLEqual(expected, result);
}
Example 9
Project: activityinfo-master File: WkbGeometryProvider.java View source code |
@Override
@LogSlow(threshold = 200)
public List<AdminGeo> getGeometries(int adminLevelId) {
try {
List<AdminGeo> list = Lists.newArrayList();
DataInputStream in = new DataInputStream(openWkb(adminLevelId));
WKBReader wkbReader = new WKBReader(geometryFactory);
int count = in.readInt();
for (int i = 0; i != count; ++i) {
int id = in.readInt();
LOGGER.info("Reading geometry for admin entity " + id);
Geometry geometry = wkbReader.read(new DataInputInStream(in));
list.add(new AdminGeo(id, geometry));
}
return list;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
Example 10
Project: geodb-master File: UnionTest.java View source code |
@Test
public void extentOnePoint() throws SQLException {
union.add(createPoint(3, 5));
Object result = union.getResult();
assertThat(result, is(not(nullValue())));
Geometry envelope = GeoDB.gFromWKB((byte[]) result);
assertThat(envelope.getArea(), is(0.0));
assertThat(envelope, is(instanceOf(Point.class)));
assertThat((Point) envelope, is(equalTo(createPoint(3, 5))));
}
Example 11
Project: hibernate-orm-master File: GeometryEquality.java View source code |
private boolean test(Geometry geom1, Geometry geom2, boolean ignoreSRID) { if (geom1 == null) { return geom2 == null; } if (geom1.isEmpty()) { return geom2.isEmpty(); } if (!ignoreSRID && !equalSRID(geom1, geom2)) { return false; } if (geom1 instanceof GeometryCollection) { if (!(geom2 instanceof GeometryCollection)) { return false; } GeometryCollection expectedCollection = (GeometryCollection) geom1; GeometryCollection receivedCollection = (GeometryCollection) geom2; for (int partIndex = 0; partIndex < expectedCollection.getNumGeometries(); partIndex++) { Geometry partExpected = expectedCollection.getGeometryN(partIndex); Geometry partReceived = receivedCollection.getGeometryN(partIndex); if (!test(partExpected, partReceived, true)) { return false; } } return true; } else { return testSimpleGeometryEquality(geom1, geom2); } }
Example 12
Project: secureOWS-master File: GeometryImpl.java View source code |
/** * <p> * The operation "distance" shall return the distance between this Geometry and another * Geometry. This distance is defined to be the greatest lower bound of the set of distances * between all pairs of points that include one each from each of the two Geometries. A * "distance" value shall be a positive number associated to distance units such as meters or * standard foot. If necessary, the second geometric object shall be transformed into the same * coordinate reference system as the first before the distance is calculated. * </p> * <p> * If the geometric objects overlap, or touch, then their distance apart shall be zero. Some * current implementations use a "negative" distance for such cases, but the approach is neither * consistent between implementations, nor theoretically viable. * </p> */ public double distance(Geometry gmo) { try { com.vividsolutions.jts.geom.Geometry jtsThis = JTSAdapter.export(this); com.vividsolutions.jts.geom.Geometry jtsThat = JTSAdapter.export(gmo); return jtsThis.distance(jtsThat); } catch (GeometryException e) { LOG.logError(e.getMessage(), e); return -1; } }
Example 13
Project: geowave-master File: FeatureBoundingBoxStatistics.java View source code |
@Override protected Envelope getEnvelope(final SimpleFeature entry) { // incorporate the bounding box of the entry's envelope final Object o; if ((persistedType != null) && (reprojectedType != null) && (transform != null)) { o = FeatureDataUtils.defaultCRSTransform(entry, persistedType, reprojectedType, transform).getAttribute(getFieldName()); } else { o = entry.getAttribute(getFieldName()); } if ((o != null) && (o instanceof Geometry)) { final Geometry geometry = (Geometry) o; if (!geometry.isEmpty()) { return geometry.getEnvelopeInternal(); } } return null; }
Example 14
Project: jeql-master File: PointHandler.java View source code |
public Geometry read(EndianDataInputStream file, GeometryFactory geometryFactory, int contentLength) throws IOException, InvalidShapefileException {
// file.setLittleEndianMode(true);
//actual number of words read (word = 16bits)
int actualReadWords = 0;
int shapeType = file.readIntLE();
actualReadWords += 2;
if (shapeType != myShapeType)
throw new InvalidShapefileException("pointhandler.read() - handler's shapetype doesnt match file's");
double x = file.readDoubleLE();
double y = file.readDoubleLE();
double m, z = Double.NaN;
actualReadWords += 8;
if (shapeType == 11) {
z = file.readDoubleLE();
actualReadWords += 4;
}
if (shapeType >= 11) {
m = file.readDoubleLE();
actualReadWords += 4;
}
//verify that we have read everything we need
while (actualReadWords < contentLength) {
int junk2 = file.readShortBE();
actualReadWords += 1;
}
return geometryFactory.createPoint(new Coordinate(x, y, z));
}
Example 15
Project: OSMemory-master File: FastAreaTest.java View source code |
@Test
public void testInside() {
Geometry box = GeometryHelper.createBoxPolygon(1, 2, 1, 2);
FastArea fastArea = new FastArea(box, new MemoryStorage());
assertFalse(fastArea.coversNode(point(0, 0)));
assertTrue(fastArea.coversNode(point(1, 1)));
assertTrue(fastArea.coversNode(point(1, 2)));
assertTrue(fastArea.coversNode(point(1.5, 1.5)));
assertTrue(fastArea.coversNode(point(1, 1.5)));
}
Example 16
Project: SES-master File: RunwayParser.java View source code |
/* (non-Javadoc) * @see org.n52.ses.enrichment.parser.AIXMAbstractGeometryParser#parseGeometries(org.apache.xmlbeans.XmlObject) */ @Override protected List<Geometry> parseGeometries(XmlObject xmlO) throws XmlException, ParseException, GMLParseException { List<Geometry> geometries = new ArrayList<Geometry>(); // parse the feature's xml-document RunwayDocument runwayDoc = RunwayDocument.Factory.parse(xmlO.xmlText()); RunwayType runway = runwayDoc.getRunway(); // parse bounded by if (geometries.size() == 0 && runway.isSetBoundedBy()) { geometries.add(super.parseBoundedBy(runway.getBoundedBy())); } return null; }
Example 17
Project: smos-box-master File: ProductNodeRenderer.java View source code |
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (!(component instanceof JLabel)) { return component; } final JLabel label = (JLabel) component; if (value instanceof ProductNode) { label.setText(((ProductNode) value).getDisplayName()); } else if (value instanceof Geometry) { label.setText(((Geometry) value).toText().substring(0, 48).concat(" ...")); } else { label.setText(""); } return label; }
Example 18
Project: cids-server-master File: RemoteTester.java View source code |
//~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param args the command line arguments * * @throws Throwable DOCUMENT ME! */ public static void main(final String[] args) throws Throwable { // NOI18N final String domain = "WUNDA_BLAU"; // security alles unsinn :-) System.setSecurityManager(new RMISecurityManager() { @Override public void checkConnect(final String host, final int port) { } @Override public void checkConnect(final String host, final int port, final Object context) { } }); // rmi registry lokaliseren final java.rmi.registry.Registry rmiRegistry = LocateRegistry.getRegistry(1099); // lookup des callservers // NOI18N final Remote r = (Remote) Naming.lookup("rmi://localhost/callServer"); // ich weiss, dass die server von callserver implementiert werden final SearchService ss = (SearchService) r; final CatalogueService cat = (CatalogueService) r; final MetaService meta = (MetaService) r; final UserService us = (UserService) r; // System.out.println("server contacted :: "+r); // Benutzergruppe anlegen (muss auf dem Server existieren) // UserGroup ug = new UserGroup(0,"Administratoren",domain ); // user anlegen muss auf dem server existieren // User u = new User(0, "admin",domain, ug ); // oder mit login // ug_domain,ug_name,u_domain,u_name,password // NOI18N final User u = us.getUser(domain, "Administratoren", domain, "admin", "x"); // NOI18N System.out.println(u + " user token retrieved"); // meta.getC // Beispiel: // hole alle Klassen einer Dom\u00E4ne // hole dir dann f\u00FCr jede Klasse ein ObjektTemplate // MetaClass[] cs = meta.getClasses(u,domain); // // for(int i=0;i<cs.length;i++) // { // System.out.println("NEW instance ::"+meta.getInstance(u,cs[i])); // // } // System.out.println("!!getInstance durchgelaufen !!"); // Beispiel: // Template f\u00FCr eine Object der ersten Klasse // MetaObject mo = meta.getInstance(u,cs[0]); // NOI18N final MetaObject mo = meta.getMetaObject(u, 5646, 6, "WUNDA_BLAU"); // NOI18N System.out.println("metaobject::" + mo); // alle attribute des Objects // ObjectAttribute[] attribs = mo.getAttribs(); // NOI18N final java.util.Collection col1 = mo.getTraversedAttributesByType(Class.forName("")); // NOI18N final java.util.Collection col2 = mo.getAttributesByType(Class.forName("com.vividsolutions.jts.geom.Geometry")); final java.util.Collection col3 = // NOI18N mo.getAttributesByType(// NOI18N Class.forName("com.vividsolutions.jts.geom.Geometry"), 1); final java.util.Collection col4 = // NOI18N mo.getAttributesByType(// NOI18N Class.forName("com.vividsolutions.jts.geom.Geometry"), 2); final java.util.Collection col5 = // NOI18N mo.getAttributesByType(// NOI18N Class.forName("com.vividsolutions.jts.geom.Geometry"), 3); Iterator iter = col1.iterator(); // NOI18N System.out.println("!!!!!!!!!!!! traversiert !!!!!!!!!!!!!!!!!!!"); while (iter.hasNext()) { System.out.println(iter.next()); } iter = col2.iterator(); // NOI18N System.out.println("!!!!!!!!!!!! level 0 !!!!!!!!!!!!!!!!!!!"); while (iter.hasNext()) { System.out.println(iter.next()); } iter = col3.iterator(); // NOI18N System.out.println("!!!!!!!!!!!! level 1 !!!!!!!!!!!!!!!!!!!"); while (iter.hasNext()) { System.out.println(iter.next()); } iter = col4.iterator(); // NOI18N System.out.println("!!!!!!!!!!!! level 2 !!!!!!!!!!!!!!!!!!!"); while (iter.hasNext()) { System.out.println(iter.next()); } iter = col5.iterator(); // NOI18N System.out.println("!!!!!!!!!!!! level 3 !!!!!!!!!!!!!!!!!!!"); while (iter.hasNext()) { System.out.println(iter.next()); } }
Example 19
Project: orbisgis-master File: GeometryTypeUtilTest.java View source code |
@Test
public void testDimensionSequence() throws Exception {
Geometry geom = wKTReader.read("POINT(0 0)");
CoordinateSequenceDimensionFilter cd = new CoordinateSequenceDimensionFilter();
geom.apply(cd);
assertTrue(cd.getDimension() == 2);
geom = wKTReader.read("LINESTRING(0 0, 0 0 1)");
cd = new CoordinateSequenceDimensionFilter();
geom.apply(cd);
assertTrue(cd.getDimension() == 3);
}
Example 20
Project: whitebox-geospatial-analysis-tools-master File: BufferVector.java View source code |
/** * Used to execute this plugin tool. */ @Override public void run() { amIActive = true; String inputFile; String outputFile; int progress; int i, j, n, FID; int oneHundredthTotal; int numRecs; ShapeType shapeType; double bufferSize = 0; GeometryFactory factory = new GeometryFactory(); com.vividsolutions.jts.geom.Geometry geometriesToBuffer = null; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputFile = args[0]; outputFile = args[1]; bufferSize = Double.parseDouble(args[2]); if (bufferSize < 0) { showFeedback("The buffer size has not been set properly."); return; } // 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(); numRecs = input.getNumberOfRecords(); oneHundredthTotal = numRecs / 100; // set up the output files of the shapefile and the dbf ShapeFile output = new ShapeFile(outputFile, ShapeType.POLYGON); output.setProjectionStringFromOtherShapefile(input); DBFField fields[] = new DBFField[1]; fields[0] = new DBFField(); fields[0].setName("FID"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setFieldLength(10); fields[0].setDecimalCount(0); String DBFName = output.getDatabaseFile(); DBFWriter writer = new DBFWriter(new File(DBFName)); writer.setFields(fields); if (shapeType.getBaseType() == ShapeType.POLYGON) { progress = 0; ArrayList<com.vividsolutions.jts.geom.Polygon> polygons = new ArrayList<>(); com.vividsolutions.jts.geom.Geometry[] recJTSPoly = null; n = 0; for (ShapeFileRecord record : input.records) { if (record.getShapeType() != ShapeType.NULLSHAPE) { recJTSPoly = record.getGeometry().getJTSGeometries(); for (int a = 0; a < recJTSPoly.length; a++) { polygons.add((com.vividsolutions.jts.geom.Polygon) recJTSPoly[a]); } } n++; if (n >= oneHundredthTotal) { n = 0; if (cancelOp) { cancelOperation(); return; } progress++; updateProgress("Reading shapefile data:", progress); } } // create an array of polygons com.vividsolutions.jts.geom.Polygon[] polygonArray = new com.vividsolutions.jts.geom.Polygon[polygons.size()]; for (i = 0; i < polygons.size(); i++) { polygonArray[i] = polygons.get(i); } polygons.clear(); geometriesToBuffer = factory.createMultiPolygon(polygonArray); } else if (shapeType.getBaseType() == ShapeType.POLYLINE) { ArrayList<LineString> lineStringList = new ArrayList<>(); com.vividsolutions.jts.geom.Geometry[] recJTSPoly = null; progress = 0; n = 0; for (ShapeFileRecord record : input.records) { if (record.getShapeType() != ShapeType.NULLSHAPE) { recJTSPoly = record.getGeometry().getJTSGeometries(); for (int a = 0; a < recJTSPoly.length; a++) { lineStringList.add((com.vividsolutions.jts.geom.LineString) recJTSPoly[a]); } } n++; if (n >= oneHundredthTotal) { n = 0; if (cancelOp) { cancelOperation(); return; } progress++; updateProgress("Reading shapefile data:", progress); } } // create an array of polygons com.vividsolutions.jts.geom.LineString[] lineStringArray = new com.vividsolutions.jts.geom.LineString[lineStringList.size()]; for (i = 0; i < lineStringList.size(); i++) { lineStringArray[i] = lineStringList.get(i); } lineStringList.clear(); geometriesToBuffer = factory.createMultiLineString(lineStringArray); } else if (shapeType.getBaseType() == ShapeType.POINT || shapeType.getBaseType() == ShapeType.MULTIPOINT) { ArrayList<com.vividsolutions.jts.geom.Point> pointList = new ArrayList<>(); com.vividsolutions.jts.geom.Geometry[] recJTSPoly = null; n = 0; progress = 0; for (ShapeFileRecord record : input.records) { if (record.getShapeType() != ShapeType.NULLSHAPE) { recJTSPoly = record.getGeometry().getJTSGeometries(); for (int a = 0; a < recJTSPoly.length; a++) { pointList.add((com.vividsolutions.jts.geom.Point) recJTSPoly[a]); } } n++; if (n >= oneHundredthTotal) { n = 0; if (cancelOp) { cancelOperation(); return; } progress++; updateProgress("Reading shapefile data:", progress); } } // create an array of polygons com.vividsolutions.jts.geom.Point[] pointArray = new com.vividsolutions.jts.geom.Point[pointList.size()]; for (i = 0; i < pointList.size(); i++) { pointArray[i] = pointList.get(i); } pointList.clear(); geometriesToBuffer = factory.createMultiPoint(pointArray); } updateProgress("Buffering data (progress will not be updated):", -1); com.vividsolutions.jts.geom.Geometry buffer = geometriesToBuffer.buffer(bufferSize); progress = 0; updateProgress("Creating new shapefile:", -1); if (buffer instanceof com.vividsolutions.jts.geom.MultiPolygon) { MultiPolygon mpBuffer = (MultiPolygon) buffer; FID = 0; n = 0; for (int a = 0; a < mpBuffer.getNumGeometries(); a++) { com.vividsolutions.jts.geom.Geometry g = mpBuffer.getGeometryN(a); if (g instanceof com.vividsolutions.jts.geom.Polygon) { com.vividsolutions.jts.geom.Polygon bufferPoly = (com.vividsolutions.jts.geom.Polygon) g; ArrayList<ShapefilePoint> pnts = new ArrayList<>(); int[] parts = new int[bufferPoly.getNumInteriorRing() + 1]; Coordinate[] buffCoords = bufferPoly.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 < bufferPoly.getNumInteriorRing(); b++) { parts[b + 1] = pnts.size(); buffCoords = bufferPoly.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()); output.addRecord(wbPoly); FID++; Object[] rowData = new Object[1]; rowData[0] = new Double(FID); writer.addRecord(rowData); if (cancelOp) { cancelOperation(); return; } n++; progress = (int) (n * 100.0 / mpBuffer.getNumGeometries()); updateProgress("Creating new shapefile:", progress); } else { // I'm really hoping this is never hit. } } } else if (buffer instanceof com.vividsolutions.jts.geom.Polygon) { com.vividsolutions.jts.geom.Polygon pBuffer = (com.vividsolutions.jts.geom.Polygon) buffer; com.vividsolutions.jts.geom.Geometry g = pBuffer.getGeometryN(0); if (g instanceof com.vividsolutions.jts.geom.Polygon) { ArrayList<ShapefilePoint> pnts = new ArrayList<>(); int[] parts = new int[pBuffer.getNumInteriorRing() + 1]; Coordinate[] buffCoords = pBuffer.getExteriorRing().getCoordinates(); 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 < pBuffer.getNumInteriorRing(); b++) { parts[b + 1] = pnts.size(); buffCoords = pBuffer.getInteriorRingN(b).getCoordinates(); 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()); output.addRecord(wbPoly); Object[] rowData = new Object[1]; rowData[0] = new Double(1); writer.addRecord(rowData); } else { // I'm really hoping this is never hit. } } output.write(); writer.write(); // returning a header file string displays the image. 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(); } }
Example 21
Project: androidol-master File: GeoRSS.java View source code |
/**
*
*/
public ArrayList<Geometry> parseGeometries(InputStream inputStream) {
try {
// Get a SAXParser from the SAXPArserFactory.
SAXParserFactory saxParserFac = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFac.newSAXParser();
// Get the XMLReader of the SAXParser we created.
XMLReader xmlReader = saxParser.getXMLReader();
// Create a new ContentHandler and apply it to the XML-Reader.
GeoRSSHandler georssHandler = new GeoRSSHandler();
xmlReader.setContentHandler(georssHandler);
// Parse the georss content
xmlReader.parse(new InputSource(inputStream));
return georssHandler.getParsedGeometries();
} catch (Exception e) {
Util.printErrorMessage(e.toString());
return null;
}
}
Example 22
Project: com.opendoorlogistics-master File: ShapeIndex.java View source code |
private void countGeoms(Geometry g) {
if (g != null) {
if (GeometryCollection.class.isInstance(g)) {
int n = g.getNumGeometries();
for (int i = 0; i < n; i++) {
countGeoms(g.getGeometryN(i));
}
} else if (Point.class.isInstance(g)) {
pointsCount++;
} else if (LineString.class.isInstance(g)) {
linestringsCount++;
} else if (Polygon.class.isInstance(g)) {
pointsCount++;
}
}
}
Example 23
Project: georefine-master File: Intersects.java View source code |
public void write(JSONWriter writer, Properties options) throws JSONException { writer.object(); writer.key("description"); writer.value("first geometry has at least one point in common with second geometry (opposite of disjoint)"); writer.key("params"); writer.value("Geometry a, Geometry b"); writer.key("returns"); writer.value("true/false"); writer.endObject(); }
Example 24
Project: geoserver-old-master File: AbstractGeometryTypeBinding.java View source code |
public Object parse(ElementInstance instance, Node node, Object value) throws Exception { try { if (node.hasAttribute("srsName")) { CRS.decode(node.getAttributeValue("srsName").toString()); } } catch (NoSuchAuthorityCodeException e) { throw new WFSException("Invalid Authority Code: " + e.getAuthorityCode(), "InvalidParameterValue"); } Geometry geometry = (Geometry) super.parse(instance, node, value); if (geometry != null) { //1. ensure a crs is set if (geometry.getUserData() == null) { //no crs set for the geometry, did we inherit one from a parent? if (crs != null) { geometry.setUserData(crs); } else { // for the moment we don't do anything since we miss the information // to infer the CRS from the feature type } } //2. ensure the coordinates of the geometry fall into valid space defined by crs CoordinateReferenceSystem crs = (CoordinateReferenceSystem) geometry.getUserData(); if (crs != null) try { JTS.checkCoordinatesRange(geometry, crs); } catch (PointOutsideEnvelopeException e) { throw new WFSException(e, "InvalidParameterValue"); } } return geometry; }
Example 25
Project: geoserver_trunk-master File: AbstractGeometryTypeBinding.java View source code |
public Object parse(ElementInstance instance, Node node, Object value) throws Exception { try { if (node.hasAttribute("srsName")) { CRS.decode(node.getAttributeValue("srsName").toString()); } } catch (NoSuchAuthorityCodeException e) { throw new WFSException("Invalid Authority Code: " + e.getAuthorityCode(), "InvalidParameterValue"); } Geometry geometry = (Geometry) super.parse(instance, node, value); if (geometry != null) { //1. ensure a crs is set if (geometry.getUserData() == null) { //no crs set for the geometry, did we inherit one from a parent? if (crs != null) { geometry.setUserData(crs); } else { // for the moment we don't do anything since we miss the information // to infer the CRS from the feature type } } //2. ensure the coordinates of the geometry fall into valid space defined by crs CoordinateReferenceSystem crs = (CoordinateReferenceSystem) geometry.getUserData(); if (crs != null) try { JTS.checkCoordinatesRange(geometry, crs); } catch (PointOutsideEnvelopeException e) { throw new WFSException(e, "InvalidParameterValue"); } } return geometry; }
Example 26
Project: geotools-cookbook-master File: BufferProcess.java View source code |
public Map<String, Object> execute(Map<String, Object> input, ProgressListener monitor) { if (started) throw new IllegalStateException("Process can only be run once"); started = true; if (monitor == null) monitor = new NullProgressListener(); try { monitor.started(); monitor.setTask(Text.text("Grabbing arguments")); monitor.progress(10.0f); Object value = input.get(BufferFactory.GEOM1.key); if (value == null) { throw new NullPointerException("geom1 parameter required"); } if (!(value instanceof Geometry)) { throw new ClassCastException("geom1 requied Geometry, not " + value); } Geometry geom1 = (Geometry) value; value = input.get(BufferFactory.BUFFER.key); if (value == null) { throw new ClassCastException("geom1 requied Geometry, not " + value); } if (!(value instanceof Number)) { throw new ClassCastException("buffer requied number, not " + value); } Double buffer = ((Number) value).doubleValue(); monitor.setTask(Text.text("Processing Buffer")); monitor.progress(25.0f); if (monitor.isCanceled()) { // user has canceled this operation return null; } Geometry resultGeom = geom1.buffer(buffer); monitor.setTask(Text.text("Encoding result")); monitor.progress(90.0f); Map<String, Object> result = new HashMap<String, Object>(); result.put(BufferFactory.RESULT.key, resultGeom); // same as 100.0f monitor.complete(); return result; } catch (Exception eek) { monitor.exceptionOccurred(eek); return null; } finally { monitor.dispose(); } }
Example 27
Project: jena-sparql-api-master File: LinkGeomizer.java View source code |
public static Map<Triple, Geometry> geomize(Iterable<Triple> triples, LookupService<Node, Geometry> lookupServiceSubjects, LookupService<Node, Geometry> lookupServiceObjects) { Map<Triple, Geometry> result = new HashMap<Triple, Geometry>(); Set<Node> subjects = new HashSet<Node>(); Set<Node> objects = new HashSet<Node>(); for (Triple triple : triples) { subjects.add(triple.getSubject()); objects.add(triple.getObject()); } Map<Node, Geometry> mapSubjects = lookupServiceSubjects.apply(subjects); Map<Node, Geometry> mapObjects = lookupServiceObjects.apply(objects); System.out.println("mapSubjects: " + mapSubjects); System.out.println("mapObjects: " + mapObjects); GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326); for (Triple triple : triples) { Geometry gs = mapSubjects.get(triple.getSubject()); Geometry go = mapObjects.get(triple.getObject()); if (gs == null || go == null) { continue; } Coordinate[] coordinates = DistanceOp.nearestPoints(gs, go); // Point ps = GeometryFactory.createPointFromInternalCoord(points[0], gs); // Point po = GeometryFactory.createPointFromInternalCoord(points[1], go); LineString lineString = gf.createLineString(coordinates); result.put(triple, lineString); } return result; }
Example 28
Project: maxwell-master File: GeometryColumnDef.java View source code |
@Override public Object asJSON(Object value) { Geometry geometry = null; if (value instanceof Geometry) { geometry = (Geometry) value; } else if (value instanceof byte[]) { byte[] bytes = (byte[]) value; // mysql sprinkles 4 mystery bytes on top of the GIS data. bytes = Arrays.copyOfRange(bytes, 4, bytes.length); final WKBReader reader = new WKBReader(); try { geometry = reader.read(bytes); } catch (ParseException e) { throw new RuntimeException("Could not parse geometry: " + e); } } else { throw new RuntimeException("Could not parse geometry column value: " + value); } return geometry.toText(); }
Example 29
Project: openjump-core-rels-master File: WarpImageToFencePlugIn.java View source code |
/**
*@inheritDoc
*/
public boolean execute(PlugInContext context) throws Exception {
RasterImageLayer rLayer = (RasterImageLayer) LayerTools.getSelectedLayerable(context, RasterImageLayer.class);
if (rLayer == null) {
//$NON-NLS-1$
context.getWorkbenchFrame().warnUser(I18N.get("pirol.plugIns.EditAttributeByFormulaPlugIn.no-layer-selected"));
return false;
}
Geometry fence = SelectionTools.getFenceGeometry(context);
Envelope envWanted = fence.getEnvelopeInternal();
rLayer.setEnvelope(envWanted);
return true;
}
Example 30
Project: spatial_statistics_for_geotools_udig-master File: FlipLineFeatureCollection.java View source code |
public SimpleFeature next() throws NoSuchElementException { SimpleFeature feature = delegate.next(); for (Object attribute : feature.getAttributes()) { if (attribute instanceof Geometry) { Geometry geometry = (Geometry) attribute; attribute = geometry.reverse(); } builder.add(attribute); } return builder.buildFeature(feature.getID()); }
Example 31
Project: wikibrain-master File: ContainmentIndex.java View source code |
public void insert(int id, Geometry geometry) { for (int i = 0; i < bufferWidths.length; i++) { Geometry exp = geometry.buffer(bufferWidths[i]); Envelope env = exp.getEnvelopeInternal(); synchronized (indexes[i]) { indexes[i].insert(env, id); expanded[i].put(id, exp); } synchronized (geometries) { geometries.put(id, geometry); } } }
Example 32
Project: cismap-commons-master File: GeomFromWktConverterTest.java View source code |
@Test
public void testConvertForward() throws Exception {
System.out.println("TEST " + getCurrentMethodName());
final GeomFromWktConverter conv = new GeomFromWktConverter();
final String wkt = "POINT(1.13 2)";
Geometry resGeom = conv.convertForward(wkt, new String[] { "4326" });
assertNotNull(resGeom);
assertEquals(4326, resGeom.getSRID());
assertEquals(1, resGeom.getCoordinates().length);
assertEquals(new Coordinate(1.13, 2), resGeom.getCoordinates()[0]);
assertEquals("Point", resGeom.getGeometryType());
final String ewkt = "SRID=3021;POINT(1.13 2)";
resGeom = conv.convertForward(ewkt, new String[] { "4326" });
assertNotNull(resGeom);
assertEquals(3021, resGeom.getSRID());
assertEquals(1, resGeom.getCoordinates().length);
assertEquals(new Coordinate(1.13, 2), resGeom.getCoordinates()[0]);
assertEquals("Point", resGeom.getGeometryType());
}
Example 33
Project: jeo-master File: GeobufReader.java View source code |
com.vividsolutions.jts.geom.Geometry decode(Geometry g) { switch(g.getType()) { case POINT: return decodePoint(g); case LINESTRING: return decodeLine(g); case POLYGON: return decodePolygon(g); case MULTIPOINT: return decodeMultiPoint(g); case MULTILINESTRING: return decodeMultiLine(g); case MULTIPOLYGON: return decodeMultiPolygon(g); case GEOMETRYCOLLECTION: return decodeCollection(g); default: throw new UnsupportedOperationException(); } }
Example 34
Project: geo-platform-master File: GPGeometryAdapter.java View source code |
@Override
public G unmarshal(String val) throws Exception {
WKTReader wktReader = new WKTReader();
Geometry the_geom = wktReader.read(val);
if (the_geom.getSRID() == 0) {
the_geom.setSRID(4326);
}
try {
return (G) the_geom;
} catch (ClassCastException e) {
throw new ParseException("WKT val is a " + the_geom.getClass().getName());
}
}
Example 35
Project: liquibase-spatial-master File: GeometryType.java View source code |
/** * @see liquibase.datatype.LiquibaseDataType#objectToSql(java.lang.Object, * liquibase.database.Database) */ @Override public String objectToSql(final Object value, final Database database) { final String returnValue; if (value instanceof Geometry) { // TODO: Tailor the output for the database. returnValue = ((Geometry) value).toText(); } else if (value instanceof String) { returnValue = value.toString(); } else if (value instanceof DatabaseFunction) { returnValue = value.toString(); } else if (value == null || value.toString().equalsIgnoreCase("null")) { returnValue = null; } else { throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass() + " to a Geometry value"); } return returnValue; }
Example 36
Project: anti-piracy-android-app-master File: GeometryDeserializer.java View source code |
public Geometry parseGeometry(JsonParser parser) throws JsonParseException, IOException { if (parser.getCurrentToken() != JsonToken.START_OBJECT) return null; String typeName = null; ArrayNode coordinates = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String name = parser.getCurrentName(); if ("type".equals(name)) { parser.nextToken(); typeName = parser.getText(); } else if ("coordinates".equals(name)) { parser.nextToken(); coordinates = parser.readValueAsTree(); } else { parser.nextToken(); parser.skipChildren(); } } Geometry geometry = null; if (typeName.equals("Point")) { geometry = geometryFactory.createPoint(new Coordinate(coordinates.get(0).asDouble(), coordinates.get(1).asDouble())); } else if (typeName.equals("MultiPoint")) { geometry = geometryFactory.createMultiPoint(parseLineString(coordinates)); } else if (typeName.equals("LineString")) { geometry = geometryFactory.createLineString(parseLineString(coordinates)); } else if (typeName.equals("MultiLineString")) { geometry = geometryFactory.createMultiLineString(parseLineStrings(coordinates)); } else if (typeName.equals("Polygon")) { geometry = parsePolygonCoordinates(coordinates); } else if (typeName.equals("MultiPolygon")) { geometry = geometryFactory.createMultiPolygon(parsePolygons(coordinates)); } else if (typeName.equals("GeometryCollection")) { geometry = geometryFactory.createGeometryCollection(parseGeometries(coordinates)); } return geometry; }
Example 37
Project: cta-otp-master File: Components.java View source code |
/**
* Get polygons covering the components of the graph. The largest component (in terms of number
* of nodes) will not overlap any other components (it will have holes); the others may overlap
* each other.
*
* @param modes
* @return
*/
@Secured({ "ROLE_USER" })
@GET
@Path("/polygons")
@Produces({ MediaType.APPLICATION_JSON })
public GraphComponentPolygons getComponentPolygons(@DefaultValue("TRANSIT,WALK") @QueryParam("modes") TraverseModeSet modes, @QueryParam("date") String date, @QueryParam("time") String time, @DefaultValue("") @QueryParam("bannedRoutes") String bannedRoutes, @QueryParam("routerId") String routerId) {
RoutingRequest options = new RoutingRequest(modes);
if (bannedRoutes.length() > 0) {
options.setBannedRoutes(bannedRoutes);
}
Graph graph = graphService.getGraph(routerId);
long dateTime = DateUtils.toDate(date, time, graph.getTimeZone()).getTime();
if (cachedPolygons == null || dateTime != cachedDateTime || !options.equals(cachedOptions)) {
cachedOptions = options;
cachedDateTime = dateTime;
cachedPolygons = AnalysisUtils.getComponentPolygons(graph, options, dateTime);
}
GraphComponentPolygons out = new GraphComponentPolygons();
out.components = new ArrayList<GraphComponent>();
for (Geometry geometry : cachedPolygons) {
GraphComponent component = new GraphComponent();
component.polygon = geometry;
out.components.add(component);
}
return out;
}
Example 38
Project: ddf-master File: GeometryAdapter.java View source code |
public static GeometryElement marshalFrom(Attribute attribute) throws CatalogTransformerException {
GeometryElement element = new GeometryElement();
element.setName(attribute.getName());
if (attribute.getValue() != null) {
for (Serializable value : attribute.getValues()) {
if (!(value instanceof String)) {
continue;
}
String wkt = (String) value;
WKTReader wktReader = new WKTReader(geometryFactory);
Geometry jtsGeometry = null;
try {
jtsGeometry = wktReader.read(wkt);
} catch (ParseException e) {
throw new CatalogTransformerException("Could not transform Metacard to XML. Invalid WKT.", e);
}
JTSToGML311GeometryConverter converter = new JTSToGML311GeometryConverter();
@SuppressWarnings("unchecked") JAXBElement<AbstractGeometryType> gmlElement = (JAXBElement<AbstractGeometryType>) converter.createElement(jtsGeometry);
GeometryElement.Value geoValue = new GeometryElement.Value();
geoValue.setGeometry(gmlElement);
((GeometryElement) element).getValue().add(geoValue);
}
}
return element;
}
Example 39
Project: disconnected-content-explorer-android-master File: GeometryDeserializer.java View source code |
public Geometry parseGeometry(JsonParser parser) throws JsonParseException, IOException { if (parser.getCurrentToken() != JsonToken.START_OBJECT) return null; String typeName = null; ArrayNode coordinates = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String name = parser.getCurrentName(); if ("type".equals(name)) { parser.nextToken(); typeName = parser.getText(); } else if ("coordinates".equals(name)) { parser.nextToken(); coordinates = parser.readValueAsTree(); } else { parser.nextToken(); parser.skipChildren(); } } Geometry geometry = null; if (typeName.equals("Point")) { geometry = geometryFactory.createPoint(new Coordinate(coordinates.get(0).asDouble(), coordinates.get(1).asDouble())); } else if (typeName.equals("MultiPoint")) { geometry = geometryFactory.createMultiPoint(parseLineString(coordinates)); } else if (typeName.equals("LineString")) { geometry = geometryFactory.createLineString(parseLineString(coordinates)); } else if (typeName.equals("MultiLineString")) { geometry = geometryFactory.createMultiLineString(parseLineStrings(coordinates)); } else if (typeName.equals("Polygon")) { geometry = parsePolygonCoordinates(coordinates); } else if (typeName.equals("MultiPolygon")) { geometry = geometryFactory.createMultiPolygon(parsePolygons(coordinates)); } else if (typeName.equals("GeometryCollection")) { geometry = geometryFactory.createGeometryCollection(parseGeometries(coordinates)); } return geometry; }
Example 40
Project: fiware-cepheus-master File: Geospatial.java View source code |
/** * Inject in Esper Configuration geospatial methods and classes * @param configuration */ public static void registerConfiguration(Configuration configuration) { // Inject methods to create Geometry variables configuration.addPlugInSingleRowFunction("polygon", Geospatial.class.getName(), "createPolygon"); configuration.addPlugInSingleRowFunction("point", Geospatial.class.getName(), "createPoint"); configuration.addPlugInSingleRowFunction("geometry", Geospatial.class.getName(), "readGeometry"); // Register Geometry class configuration.addImport(Geometry.class.getName()); }
Example 41
Project: GeoEnrichment-master File: SearchShapefilePolygon.java View source code |
public void visit(final Feature feature) { final Geometry geometry = (Geometry) feature.getProperty(m_geometryName).getValue(); if (point.within(geometry)) { m_found = true; for (final ColumnInterface column : columnList) { final Property property = feature.getProperty(column.getQualifier()); if (property != null) { column.setWeight(column.toDouble(property.getValue())); } } } }
Example 42
Project: geofence-master File: GeometryUtility.java View source code |
/** * Project geometry. * * @param originalGeom * the original geom * @param srcCRSCode * the src crs code * @param trgCRSCode * the trg crs code * @return the geometry * @throws NoSuchAuthorityCodeException * the no such authority code exception * @throws FactoryException * the factory exception * @throws MismatchedDimensionException * the mismatched dimension exception * @throws TransformException * the transform exception */ public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode, String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException, TransformException { Geometry projectedGeometry = null; final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true); // converting geometries into a linear system try { projectedGeometry = JTS.transform(originalGeom, transform); } catch (Exception e) { GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326); WKTReader reader = new WKTReader(geometryFactory); try { Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))"); projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon), transform); } catch (Exception ex) { throw new RuntimeException(ex); } } return projectedGeometry; }
Example 43
Project: GeoGig-master File: SpatialOps.java View source code |
/** * Creates and returns a geometry out of bounds (a point if bounds.getSpan(0) == * bounds.getSpan(1) == 0D, a polygon otherwise), setting the bounds * {@link BoundingBox#getCoordinateReferenceSystem() CRS} as the geometry's * {@link Geometry#getUserData() user data}. * * @param bounds the bounding box to build from * @return the newly constructed geometry */ public static Geometry toGeometry(final BoundingBox bounds) { if (bounds == null) { return null; } Geometry geom; if (bounds.getSpan(0) == 0D && bounds.getSpan(1) == 0D) { geom = gfac.createPoint(new Coordinate(bounds.getMinX(), bounds.getMinY())); } else { geom = JTS.toGeometry(bounds, gfac); } geom.setUserData(bounds.getCoordinateReferenceSystem()); return geom; }
Example 44
Project: geomajas-project-client-gwt-master File: GeometryUtilsCommand.java View source code |
@Override public void execute(final GeometryUtilsRequest request, final GeometryUtilsResponse response) throws Exception { if (request.getGeometries() != null && request.getGeometries().length > 0) { int geomCount = request.getGeometries().length; log.debug("GeometryUtilsCommand for " + geomCount + " geometries."); if (request.getActionFlags() == 0) { response.setGeometries(request.getGeometries()); } // convert to internal Geometry[] lastResult = new Geometry[geomCount]; org.geomajas.geometry.Geometry[] dtoGeoms = request.getGeometries(); for (int i = 0; i < geomCount; i++) { lastResult[i] = converter.toInternal(dtoGeoms[i]); } List<Geometry[]> intermediateResults = new ArrayList<Geometry[]>(); // do merge before buffer if ((request.getActionFlags() & GeometryUtilsRequest.ACTION_MERGE) > 0) { lastResult = merge(lastResult); intermediateResults.add(lastResult); } if ((request.getActionFlags() & GeometryUtilsRequest.ACTION_BUFFER) > 0) { lastResult = buffer(lastResult, request.getBuffer(), request.getBufferQuadrantSegments()); intermediateResults.add(lastResult); } // -- other actions here // ---------------------------------------------------------- List<org.geomajas.geometry.Geometry> dtoResult = new ArrayList<org.geomajas.geometry.Geometry>(); if (request.isIntermediateResults()) { for (Geometry[] geometries : intermediateResults) { for (Geometry geometry : geometries) { dtoResult.add(converter.toDto(geometry)); } } } else { for (Geometry geometry : lastResult) { dtoResult.add(converter.toDto(geometry)); } } response.setGeometries(dtoResult.toArray(new org.geomajas.geometry.Geometry[dtoResult.size()])); } }
Example 45
Project: geopaparazzi-master File: PrecisionReducerCoordinateOperation.java View source code |
public Coordinate[] edit(Coordinate[] coordinates, Geometry geom) {
if (coordinates.length == 0)
return null;
Coordinate[] reducedCoords = new Coordinate[coordinates.length];
// copy coordinates and reduce
for (int i = 0; i < coordinates.length; i++) {
Coordinate coord = new Coordinate(coordinates[i]);
targetPM.makePrecise(coord);
reducedCoords[i] = coord;
}
// remove repeated points, to simplify returned geometry as much as possible
CoordinateList noRepeatedCoordList = new CoordinateList(reducedCoords, false);
Coordinate[] noRepeatedCoords = noRepeatedCoordList.toCoordinateArray();
/**
* Check to see if the removal of repeated points collapsed the coordinate
* List to an invalid length for the type of the parent geometry. It is not
* necessary to check for Point collapses, since the coordinate list can
* never collapse to less than one point. If the length is invalid, return
* the full-length coordinate array first computed, or null if collapses are
* being removed. (This may create an invalid geometry - the client must
* handle this.)
*/
int minLength = 0;
if (geom instanceof LineString)
minLength = 2;
if (geom instanceof LinearRing)
minLength = 4;
Coordinate[] collapsedCoords = reducedCoords;
if (removeCollapsed)
collapsedCoords = null;
// return null or orginal length coordinate array
if (noRepeatedCoords.length < minLength) {
return collapsedCoords;
}
// ok to return shorter coordinate array
return noRepeatedCoords;
}
Example 46
Project: geoserver-2.0.x-master File: AbstractGeometryTypeBinding.java View source code |
public Object parse(ElementInstance instance, Node node, Object value) throws Exception { try { if (node.hasAttribute("srsName")) { CRS.decode(node.getAttributeValue("srsName").toString()); } } catch (NoSuchAuthorityCodeException e) { throw new WFSException("Invalid Authority Code: " + e.getAuthorityCode(), "InvalidParameterValue"); } Geometry geometry = (Geometry) super.parse(instance, node, value); if (geometry != null) { //1. ensure a crs is set if (geometry.getUserData() == null) { //no crs set for the geometry, did we inherit one from a parent? if (crs != null) { geometry.setUserData(crs); } else { // for the moment we don't do anything since we miss the information // to infer the CRS from the feature type } } //2. ensure the coordinates of the geometry fall into valid space defined by crs CoordinateReferenceSystem crs = (CoordinateReferenceSystem) geometry.getUserData(); if (crs != null) try { JTS.checkCoordinatesRange(geometry, crs); } catch (PointOutsideEnvelopeException e) { throw new WFSException(e, "InvalidParameterValue"); } } return geometry; }
Example 47
Project: geoserver-enterprise-master File: GeometryProcessWPSTest.java View source code |
@Test
public void testExecuteBuffer() throws Exception {
String xml = "<wps:Execute service='WPS' version='1.0.0' xmlns:wps='http://www.opengis.net/wps/1.0.0' " + "xmlns:ows='http://www.opengis.net/ows/1.1'>" + "<ows:Identifier>JTS:buffer</ows:Identifier>" + "<wps:DataInputs>" + "<wps:Input>" + "<ows:Identifier>geom</ows:Identifier>" + "<wps:Data>" + "<wps:ComplexData mimeType=\"application/wkt\">" + "<![CDATA[POINT(0 0)]]>" + "</wps:ComplexData>" + "</wps:Data>" + "</wps:Input>" + "<wps:Input>" + "<ows:Identifier>distance</ows:Identifier>" + "<wps:Data>" + "<wps:LiteralData>1</wps:LiteralData>" + "</wps:Data>" + "</wps:Input>" + "<wps:Input>" + "<ows:Identifier>capStyle</ows:Identifier>" + "<wps:Data>" + "<wps:LiteralData>Round</wps:LiteralData>" + "</wps:Data>" + "</wps:Input>" + "</wps:DataInputs>" + "<wps:ResponseForm>" + " <wps:RawDataOutput mimeType=\"application/wkt\">" + " <ows:Identifier>result</ows:Identifier>" + " </wps:RawDataOutput>" + " </wps:ResponseForm>" + "</wps:Execute>";
MockHttpServletResponse response = postAsServletResponse("wps", xml);
// System.out.println(response.getOutputStreamContent());
assertEquals("application/wkt", response.getContentType());
Geometry g = new WKTReader().read(response.getOutputStreamContent());
assertTrue(g instanceof Polygon);
}
Example 48
Project: gig-master File: SpatialOps.java View source code |
/** * Creates and returns a geometry out of bounds (a point if bounds.getSpan(0) == * bounds.getSpan(1) == 0D, a polygon otherwise), setting the bounds * {@link BoundingBox#getCoordinateReferenceSystem() CRS} as the geometry's * {@link Geometry#getUserData() user data}. * * @param bounds the bounding box to build from * @return the newly constructed geometry */ public static Geometry toGeometry(final BoundingBox bounds) { if (bounds == null) { return null; } Geometry geom; if (bounds.getSpan(0) == 0D && bounds.getSpan(1) == 0D) { geom = gfac.createPoint(new Coordinate(bounds.getMinX(), bounds.getMinY())); } else { geom = JTS.toGeometry(bounds, gfac); } geom.setUserData(bounds.getCoordinateReferenceSystem()); return geom; }
Example 49
Project: hale-master File: SpatiaLiteSupportVersion4.java View source code |
/** * @see eu.esdihumboldt.hale.io.jdbc.spatialite.internal.AbstractSpatiaLiteSupport#getGeometryType(java.lang.Object) */ @Override protected Class<? extends Geometry> getGeometryType(Object type) { Integer geomType = Integer.class.cast(type); Class<? extends Geometry> geometryClass = null; int geomSelector = geomType % 1000; switch(geomSelector) { case 1: geometryClass = Point.class; break; case 2: geometryClass = LineString.class; break; case 3: geometryClass = Polygon.class; break; case 4: geometryClass = MultiPoint.class; break; case 5: geometryClass = MultiLineString.class; break; case 6: geometryClass = MultiPolygon.class; break; case 7: geometryClass = GeometryCollection.class; break; case 0: geometryClass = Geometry.class; break; default: // should never happen break; } return geometryClass; }
Example 50
Project: InSpider-master File: GeneralizeWriter.java View source code |
@Override public void run() { logger.debug("starting"); try { CopyManager copyManager = new CopyManager(connection); StringBuilder queryBuilder = new StringBuilder("copy "); queryBuilder.append(destination); queryBuilder.append(" ("); for (int i = 0; i < columnNames.length; i++) { if (i != 0) { queryBuilder.append(", "); } queryBuilder.append(columnNames[i]); } if (columnNames.length > 0) { queryBuilder.append(", "); } queryBuilder.append("geometry) from stdin csv"); CopyIn copyIn = copyManager.copyIn(queryBuilder.toString()); CopyInOutputStream outputStream = new CopyInOutputStream(copyIn); Writer writer = new OutputStreamWriter(outputStream, "utf-8"); PrintWriter printWriter = new PrintWriter(writer); logger.debug("database connection established"); long featureCounter = 0; for (; ; ) { Event event = eventQueue.take(); logger.debug("event received"); if (event instanceof GeometryResult) { GeometryResult geometryResult = (GeometryResult) event; Geometry geometry = geometryResult.getGeometry(); String[] columnValues = geometryResult.getColumnValues(); for (int i = 0; i < geometry.getNumGeometries(); i++) { String wkt = wktWriter.write(geometry.getGeometryN(i)); org.postgis.Geometry pgGeometry = PGgeometry.geomFromString(wkt); pgGeometry.setSrid(28992); featureCounter++; for (int j = 0; j < columnValues.length; j++) { if (j != 0) { printWriter.print(','); } String columnValue = columnValues[j]; if (columnValue != null) { printWriter.print('"'); printWriter.print(columnValue); printWriter.print('"'); } } if (columnValues.length > 0) { printWriter.print(','); } printWriter.print('"'); printWriter.print(binaryWriter.writeHexed(pgGeometry)); printWriter.println('"'); } semaphore.release(); logger.debug("geometry received (" + semaphore.availablePermits() + ")"); } else if (event instanceof Finalize) { logger.debug("finalize event received"); break; } else { logger.debug("Unknown event type: " + event.getClass().getCanonicalName()); } } printWriter.close(); logger.debug("finished: " + featureCounter + " geometries written"); semaphore.release(); } catch (Exception e) { logger.debug("couldn't write generalized geometrie", e); } }
Example 51
Project: ISDM-master File: JTSTools.java View source code |
/** * Create a JTS Polygon form a GMLShape. * @param shape * The shape to convert. * @return Polygon geometry. * @throws ValidationException */ public static Geometry shapeToPolygon(GMLShape shape) throws ValidationException { LineSequencer seq = new LineSequencer(); for (GMLDirectedEdge e : shape.getEdges()) { Coordinate[] coord = new Coordinate[2]; coord[0] = nodeToCoordinate(e.getStartNode()); coord[1] = nodeToCoordinate(e.getEndNode()); if (coord[0].equals(coord[1])) { throw new ValidationException(e.getEdge().getID(), "Zero length edge."); } seq.add(geomFactory.createLineString(coord)); } try { if (!seq.isSequenceable()) { throw new ValidationException(shape.getID(), "Outline is not a single line."); } } catch (AssertionFailedException e) { throw new ValidationException(shape.getID(), "Could not get outline: " + e.getMessage()); } Geometry line = seq.getSequencedLineStrings(); CoordinateList coord = new CoordinateList(line.getCoordinates()); coord.closeRing(); // CHECKSTYLE:OFF:MagicNumber if (coord.size() < 4) { // CHECKSTYLE:ON:MagicNumber throw new ValidationException(shape.getID(), "Degenerate Shape"); } Geometry ring = geomFactory.createLinearRing(coord.toCoordinateArray()); return geomFactory.createPolygon((LinearRing) ring, null); }
Example 52
Project: lod4wfs-master File: TestGeoTools.java View source code |
public static void main(String[] args) throws ParseException, NoSuchAuthorityCodeException, FactoryException, IOException, SchemaException, java.text.ParseException {
String wktGeometry = "POLYGON ((-61.6866679999999974 17.0244409999999995, -61.8872220000000013 17.1052740000000014, -61.7944490000000002 17.1633299999999984, -61.6866679999999974 17.0244409999999995)) POLYGON ((-61.7291719999999984 17.6086080000000003, -61.8530579999999972 17.5830540000000006, -61.8730619999999973 17.7038879999999992, -61.7291719999999984 17.6086080000000003))";
WKTReader wktR = new WKTReader();
Geometry geom = wktR.read(wktGeometry);
// write JTS to string
GMLWriter gmlW = new GMLWriter(true);
gmlW.setSrsName("<http://www.opengis.net/def/crs/EPSG/0/4326>");
String gml = gmlW.write(geom);
System.out.println(gml);
GeometryBuilder gb = new GeometryBuilder(gml);
WKTParser wktp = new WKTParser(gb);
wktp.parse(wktGeometry);
}
Example 53
Project: lodes-processor-master File: Blocks.java View source code |
public void load(File blockShapefile, Geometry boundary) throws IOException, FactoryException { System.out.println("loading " + blockShapefile.getName()); PreparedPolygon preparedBoundary = null; if (boundary != null) preparedBoundary = new PreparedPolygon((Polygonal) boundary); Map map = new HashMap(); map.put("url", blockShapefile.toURI().toURL()); DataStore dataStore = DataStoreFinder.getDataStore(map); SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]); SimpleFeatureType schema = featureSource.getSchema(); CoordinateReferenceSystem shpCRS = schema.getCoordinateReferenceSystem(); MathTransform transform = CRS.findMathTransform(shpCRS, wgsCRS, true); SimpleFeatureCollection collection = featureSource.getFeatures(); SimpleFeatureIterator iterator = collection.features(); Integer skippedFeatures = 0; Integer clipedFeatures = 0; try { while (iterator.hasNext()) { try { SimpleFeature feature = iterator.next(); String geoId = (String) feature.getAttribute("GEOID10"); Long areaLand = (Long) feature.getAttribute("ALAND10"); Long areaWater = (Long) feature.getAttribute("AWATER10"); Double percentLand = (double) (areaLand / (areaLand + areaWater)); Geometry geom = JTS.transform((Geometry) feature.getDefaultGeometry(), transform); Point centroid = geom.getCentroid(); if (preparedBoundary == null || (preparedBoundary.contains(centroid))) lodesBlocks.put(geoId, new IndicatorItem(geoId, geom, percentLand)); else clipedFeatures++; } catch (Exception e) { skippedFeatures++; System.out.println(e.toString()); continue; } } } finally { iterator.close(); } dataStore.dispose(); System.out.println("Features imported: " + lodesBlocks.size() + "(" + skippedFeatures + " skipped, " + clipedFeatures + " outside survey area)"); }
Example 54
Project: magnificent-mileage-master File: GraphUtils.java View source code |
private static GeometryCollection geometryCollectionFromVertices(Graph graph) { GeometryFactory gf = GeometryUtils.getGeometryFactory(); Collection<Vertex> vertices = graph.getVertices(); Geometry[] points = new Geometry[vertices.size()]; int i = 0; for (Vertex v : vertices) { points[i++] = gf.createPoint(v.getCoordinate()); } GeometryCollection geometries = new GeometryCollection(points, gf); return geometries; }
Example 55
Project: MapStoreMobile-master File: GsonUtil.java View source code |
public static Gson createFeatureGson() { Type resourceListType = new TypeToken<List<Resource>>() { }.getType(); Type attributeListType = new TypeToken<List<Attribute>>() { }.getType(); return new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(// GeoStore compliant typeAdapter resourceListType, new GeoStoreResourceTypeAdapter()).registerTypeAdapter(attributeListType, new GeoStoreAttributeTypeAdapter()).registerTypeHierarchyAdapter(// GeoJson serializer/deserializer Geometry.class, new GeometryJsonSerializer()).registerTypeHierarchyAdapter(Geometry.class, new GeometryJsonDeserializer()).create(); }
Example 56
Project: occurrence-master File: ContainsUDF.java View source code |
public BooleanWritable evaluate(Text geometryAsWKT, Double latitude, Double longitude) { isContained.set(false); try { // sanitize the input if (geometryAsWKT == null || latitude == null || longitude == null || latitude > 90 || latitude < -90 || longitude > 180 || longitude < -180) { return isContained; } String geoWKTStr = geometryAsWKT.toString(); Geometry geom = geometryCache.get(geoWKTStr); if (geom == null) { geom = wktReader.read(geoWKTStr); geometryCache.put(geoWKTStr, geom); } // support any geometry - up to the user to make a sensible query Geometry point = geometryFactory.createPoint(new Coordinate(longitude, latitude)); isContained.set(geom.contains(point)); } catch (ParseException e) { LOG.error("Invalid geometry received: {}", geometryAsWKT.toString(), e); } catch (Exception e) { LOG.error("Error applying UDF", e); } return isContained; }
Example 57
Project: olca-modules-master File: MultiGeometryTest.java View source code |
@Test public void noIntersection() throws Exception { String kml = Tests.getKml("multipolygon.kml"); KmlFeature feature = KmlFeature.parse(kml); Geometry multi = feature.geometry; Geometry noIntersect = Tests.createPolygon(COORDS_NO_INTERSECT); double area = multi.intersection(noIntersect).getArea(); Assert.assertEquals(0d, area, 0d); }
Example 58
Project: OpenTripPlanner-master File: ShapefileBoundaryResolver.java View source code |
@Override public String resolve(double x, double y) { System.out.println("x=" + x + ", y=" + y); FeatureIterator<Feature> iterator = collection.features(); while (iterator.hasNext()) { SimpleFeature feature = (SimpleFeature) iterator.next(); Geometry geom = (Geometry) feature.getDefaultGeometry(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); Coordinate coord = new Coordinate(x, y); Point point = geometryFactory.createPoint(coord); //System.out.println("checking "+point.toString()); if (geom.contains(point)) { return feature.getAttribute(this.nameField).toString(); } } return null; }
Example 59
Project: Planner-master File: ShapefileBoundaryResolver.java View source code |
@Override public String resolve(double x, double y) { System.out.println("x=" + x + ", y=" + y); FeatureIterator<Feature> iterator = collection.features(); while (iterator.hasNext()) { SimpleFeature feature = (SimpleFeature) iterator.next(); Geometry geom = (Geometry) feature.getDefaultGeometry(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); Coordinate coord = new Coordinate(x, y); Point point = geometryFactory.createPoint(coord); //System.out.println("checking "+point.toString()); if (geom.contains(point)) { return feature.getAttribute(this.nameField).toString(); } } return null; }
Example 60
Project: ps-framework-master File: GeoJSONEncoding.java View source code |
@Override public <T> String encode(T object) throws EncodeException { if (object instanceof Geometry) { GeoJtsConverter converter = new GeoJtsConverter(); GeoObject geo = converter.fromJts((Geometry) object); GeoJsonEncoder encoder = GeoJsonEncoder.create(); return encoder.encode(geo); } else { throw new EncodeException("Cannot encode " + object.getClass().getSimpleName() + " as GeoJSON"); } }
Example 61
Project: spatial4j-master File: JtsBinaryCodecTest.java View source code |
Geometry randomGeometry(int points) {
//a circle
JtsSpatialContext ctx = (JtsSpatialContext) super.ctx;
GeometricShapeFactory gsf = new GeometricShapeFactory(ctx.getGeometryFactory());
gsf.setCentre(new Coordinate(0, 0));
//diameter
gsf.setSize(180);
gsf.setNumPoints(points);
return gsf.createCircle();
}
Example 62
Project: udig-community-master File: TargetLayerDissolveValidator.java View source code |
/** * Check the target geometry compatibility for dissolve operation. * * @return */ @Override public boolean validGeometryCompatible(ILayer sourceLayer) { SimpleFeatureType sourceType = sourceLayer.getSchema(); GeometryDescriptor firstGeomAttr = sourceType.getGeometryDescriptor(); Class<? extends Geometry> sourceGeomClass = (Class<? extends Geometry>) firstGeomAttr.getType().getBinding(); Class<? extends Geometry> targetGeomClass = null; if (targetLayer != null) { SimpleFeatureType targetType = targetLayer.getSchema(); GeometryDescriptor secondGeomAttr = targetType.getGeometryDescriptor(); targetGeomClass = (Class<? extends Geometry>) secondGeomAttr.getType().getBinding(); } else { targetGeomClass = this.targetGeometryClass; } if (targetGeomClass.equals(Geometry.class)) { return true; } if ((sourceGeomClass.equals(Polygon.class) || sourceGeomClass.equals(MultiPolygon.class)) && (!targetGeomClass.equals(Polygon.class) && !targetGeomClass.equals(MultiPolygon.class))) { return false; } if ((sourceGeomClass.equals(LineString.class) || sourceGeomClass.equals(MultiLineString.class)) && (!targetGeomClass.equals(LineString.class) && !targetGeomClass.equals(MultiLineString.class))) { return false; } if ((sourceGeomClass.equals(Point.class) || sourceGeomClass.equals(MultiPoint.class)) && (!targetGeomClass.equals(Point.class) && !targetGeomClass.equals(MultiPoint.class))) { return false; } return true; }
Example 63
Project: vtm-master File: JtsLayer.java View source code |
protected void addPolygon(Task t, Geometry g, MeshBucket ml, LineBucket ll) {
mGeom.clear();
mGeom.startPolygon();
CoordinatePath p = CoordinatePath.create(g);
if (mMinX > 0 || mMinY > 0)
p.generalize(mMinX, mMinY);
if (transformPath(t.position, mGeom, p) < 3)
return;
if (!mClipper.clip(mGeom))
return;
mSimpVW.simplify(mGeom, 0.1f);
mSimpDP.simplify(mGeom, 0.5f);
ll.addLine(mGeom);
ml.addMesh(mGeom);
}
Example 64
Project: ddf-catalog-master File: GeometryAdapter.java View source code |
public static GeometryElement marshalFrom(Attribute attribute) throws CatalogTransformerException {
GeometryElement element = new GeometryElement();
element.setName(attribute.getName());
if (attribute.getValue() != null) {
for (Serializable value : attribute.getValues()) {
if (!(value instanceof String)) {
continue;
}
String wkt = (String) value;
WKTReader wktReader = new WKTReader(geometryFactory);
Geometry jtsGeometry = null;
try {
jtsGeometry = wktReader.read(wkt);
} catch (ParseException e) {
throw new CatalogTransformerException("Could not transform Metacard to XML. Invalid WKT.", e);
}
JTSToGML311GeometryConverter converter = new JTSToGML311GeometryConverter();
@SuppressWarnings("unchecked") JAXBElement<AbstractGeometryType> gmlElement = (JAXBElement<AbstractGeometryType>) converter.createElement(jtsGeometry);
GeometryElement.Value geoValue = new GeometryElement.Value();
geoValue.setGeometry(gmlElement);
((GeometryElement) element).getValue().add(geoValue);
}
}
return element;
}
Example 65
Project: GoFleetLSServer-master File: GeoUtil.java View source code |
public static com.vividsolutions.jts.geom.Geometry getGeometry(PositionType position) { Geometry g = null; if (position.getPoint() != null) { if (position.getPoint().getCoord() != null && position.getPoint().getCoord().getX() != null) { g = geomFact.createPoint(new Coordinate(position.getPoint().getCoord().getX().doubleValue(), position.getPoint().getCoord().getY().doubleValue())); } else if (position.getPoint().getPos() != null && position.getPoint().getPos().getValue() != null && position.getPoint().getPos().getValue().size() == 2) { g = geomFact.createPoint(new Coordinate(position.getPoint().getPos().getValue().get(0), position.getPoint().getPos().getValue().get(1))); } } else if (position.getPolygon() != null) { PolygonType polygon = position.getPolygon(); List<LinearRing> interiorRings = new LinkedList<LinearRing>(); polygon.getInterior(); // TODO LinearRing[] holes = interiorRings.toArray(new LinearRing[] {}); List<Coordinate> coordinateList = new LinkedList<Coordinate>(); AbstractRingPropertyType exterior = polygon.getExterior().getValue(); LinearRingType ring = (LinearRingType) exterior.getRing().getValue(); for (CoordType coord : ring.getCoord()) { coordinateList.add(new Coordinate(coord.getX().doubleValue(), coord.getY().doubleValue())); } Coordinate[] coordinates = coordinateList.toArray(new Coordinate[] {}); LinearRing shell = geomFact.createLinearRing(coordinates); g = geomFact.createPolygon(shell, holes); } return g; }
Example 66
Project: Mason-master File: GeoToolsImporter.java View source code |
public static void read(final URL input, GeomVectorField field, final Bag masked) throws FileNotFoundException { try { Map<String, Serializable> connectParameters = new HashMap<String, Serializable>(); connectParameters.put("url", input); DataStore dataStore = DataStoreFinder.getDataStore(connectParameters); // we are now connected String[] typeNames = dataStore.getTypeNames(); String typeName = typeNames[0]; FeatureSource<SimpleFeatureType, SimpleFeature> featureSource; FeatureCollection<SimpleFeatureType, SimpleFeature> collection; FeatureIterator<SimpleFeature> iterator; featureSource = dataStore.getFeatureSource(typeName); collection = featureSource.getFeatures(); iterator = collection.features(); try { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); MasonGeometry mg = new MasonGeometry(geometry); mg.addAttributes(readAttributes(feature, masked)); field.addGeometry(mg); } } finally { if (iterator != null) { iterator.close(); } } } catch (Exception e) { System.out.println("Exception in GeoToolsImportor::ingest:"); e.printStackTrace(); } }
Example 67
Project: cassandra-lucene-index-master File: GeospatialUtilsJTS.java View source code |
/**
* Returns the {@link JtsGeometry} represented by the specified WKT text.
*
* @param context the JTS spatial context
* @param string the WKT text
* @return the parsed geometry
*/
public static JtsGeometry geometryFromWKT(JtsSpatialContext context, String string) {
if (StringUtils.isBlank(string)) {
throw new IndexException("Shape shouldn't be blank");
}
try {
GeometryFactory geometryFactory = context.getGeometryFactory();
WKTReader reader = new WKTReader(geometryFactory);
Geometry geometry = reader.read(string);
return context.makeShape(geometry);
} catch (ParseExceptionIllegalArgumentException | e) {
throw new IndexException(e, "Shape '%s' is not parseable", string);
}
}
Example 68
Project: cids-custom-switchon-master File: NamedAreaIconFactory.java View source code |
@Override public Icon getLeafObjectNodeIcon(final ObjectTreeNode otn) { try { final CidsBean bean = otn.getMetaObject().getBean(); final Geometry geom = (Geometry) bean.getProperty("area.geo_field"); final Envelope env = geom.getEnvelopeInternal(); final double scale = Math.min(16 / env.getWidth(), 16 / env.getHeight()); final double xoff = 0 - (scale * env.getMinX()); final double yoff = env.getMaxY() * scale; final AffineTransform at = new AffineTransform(scale, 0, 0, -scale, xoff, yoff); final LiteShape shape = new LiteShape(geom, at, false); final int dw = (int) Math.ceil(geom.getEnvelopeInternal().getWidth() * scale); final int dh = (int) Math.ceil(geom.getEnvelopeInternal().getHeight() * scale); final BufferedImage biShape = new BufferedImage(dw, dh, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2dShape = (Graphics2D) biShape.getGraphics(); final Paint paint = new Color(153, 153, 255); g2dShape.setPaint(paint); g2dShape.fill(shape); g2dShape.setPaint(Color.BLACK); g2dShape.draw(shape); final BufferedImage bi = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = (Graphics2D) bi.getGraphics(); final int x = (bi.getWidth() - biShape.getWidth()) / 2; final int y = (bi.getHeight() - biShape.getHeight()) / 2; g2d.drawImage(biShape, x, y, null); return new ImageIcon(bi); } catch (final Exception e) { LOG.error("cannot create catchment area icon", e); return null; } }
Example 69
Project: constellation-master File: CrsAdjustFilterVisitor.java View source code |
@Override public Object visit(final Literal expression, final Object extraData) { Object obj = expression.getValue(); try { if (obj instanceof BoundingBox) { BoundingBox bbox = (BoundingBox) obj; if (CRS.equalsIgnoreMetadata(bbox.getCoordinateReferenceSystem(), baseCrs)) { final Envelope e = CRS.transform(bbox, replacementCrs); final BoundingBox rbbox = new DefaultBoundingBox(replacementCrs); rbbox.setBounds(new DefaultBoundingBox(e)); obj = rbbox; } } else if (obj instanceof Geometry) { Geometry geo = (Geometry) obj; geo = (Geometry) geo.clone(); final CoordinateReferenceSystem geoCrs = JTS.findCoordinateReferenceSystem(geo); if (geoCrs == null) { JTS.setCRS(geo, replacementCrs); } else if (CRS.equalsIgnoreMetadata(geoCrs, baseCrs)) { geo = JTS.transform(geo, CRS.findMathTransform(baseCrs, replacementCrs)); JTS.setCRS(geo, replacementCrs); } obj = geo; } } catch (FactoryExceptionTransformException | ex) { Logging.getLogger("org.constellation.wfs.ws").log(Level.SEVERE, null, ex); } return getFactory(extraData).literal(obj); }
Example 70
Project: DBSCAN4LBSN-master File: PrecisionReducerCoordinateOperation.java View source code |
public Coordinate[] edit(Coordinate[] coordinates, Geometry geom) {
if (coordinates.length == 0)
return null;
Coordinate[] reducedCoords = new Coordinate[coordinates.length];
// copy coordinates and reduce
for (int i = 0; i < coordinates.length; i++) {
Coordinate coord = new Coordinate(coordinates[i]);
targetPM.makePrecise(coord);
reducedCoords[i] = coord;
}
// remove repeated points, to simplify returned geometry as much as possible
CoordinateList noRepeatedCoordList = new CoordinateList(reducedCoords, false);
Coordinate[] noRepeatedCoords = noRepeatedCoordList.toCoordinateArray();
/**
* Check to see if the removal of repeated points collapsed the coordinate
* List to an invalid length for the type of the parent geometry. It is not
* necessary to check for Point collapses, since the coordinate list can
* never collapse to less than one point. If the length is invalid, return
* the full-length coordinate array first computed, or null if collapses are
* being removed. (This may create an invalid geometry - the client must
* handle this.)
*/
int minLength = 0;
if (geom instanceof LineString)
minLength = 2;
if (geom instanceof LinearRing)
minLength = 4;
Coordinate[] collapsedCoords = reducedCoords;
if (removeCollapsed)
collapsedCoords = null;
// return null or orginal length coordinate array
if (noRepeatedCoords.length < minLength) {
return collapsedCoords;
}
// ok to return shorter coordinate array
return noRepeatedCoords;
}
Example 71
Project: ecdr-master File: MultiPolygon.java View source code |
@Override
public Map toJsonMap() {
Map map = new HashMap();
if (TYPE.equals(getGeometry().getGeometryType())) {
map.put(TYPE_KEY, TYPE);
List<List> listOfPolygons = new ArrayList<List>();
for (int i = 0; i < getGeometry().getNumGeometries(); i++) {
List polygon = buildJsonPolygon((com.vividsolutions.jts.geom.Polygon) getGeometry().getGeometryN(i));
listOfPolygons.add(polygon);
}
map.put(COORDINATES_KEY, listOfPolygons);
} else {
throw new UnsupportedOperationException("Geometry is not a " + TYPE);
}
return map;
}
Example 72
Project: eMonocot-master File: LocationTest.java View source code |
/** * */ @Test public final void testCompareGeography() throws Exception { List<Geometry> list = new ArrayList<Geometry>(); list.add(Location.EUROPE.getEnvelope()); list.add(Location.AFRICA.getEnvelope()); list.add(Location.CHINA.getEnvelope()); list.add(Location.MACARONESIA.getEnvelope()); list.add(Location.EASTERN_CANADA.getEnvelope()); list.add(Location.FRA.getEnvelope()); list.add(Location.ABT.getEnvelope()); list.add(Location.GRB.getEnvelope()); list.add(Location.IRE.getEnvelope()); list.add(Location.ALG.getEnvelope()); GeometryCollection geometryCollection = new GeometryCollection(list.toArray(new Geometry[list.size()]), new GeometryFactory()); Coordinate[] envelope = geometryCollection.getEnvelope().getCoordinates(); for (Coordinate c : envelope) { logger.debug(Math.round(c.x) + " " + Math.round(c.y)); } }
Example 73
Project: gazetteer-master File: GeometryUtils.java View source code |
public static Geometry parseGeometry(JSONObject geom) {
if (geom != null) {
String type = geom.optString("type").toLowerCase();
JSONArray coords = geom.getJSONArray("coordinates");
switch(type) {
case "point":
return factory.createPoint(new Coordinate(coords.getDouble(0), coords.getDouble(1)));
case "linestring":
return getLineStringGeometry(coords);
case "polygon":
return getPolygonGeometry(coords);
case "multipolygon":
return getMultiPolygonGeometry(coords);
}
}
return null;
}
Example 74
Project: geostore-master File: XMultiPolygonAdapter.java View source code |
/*
* (non-Javadoc) @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
*/
@Override
public MultiPolygon unmarshal(String val) throws ParseException {
WKTReader wktReader = new WKTReader();
Geometry the_geom = wktReader.read(val);
if (the_geom.getSRID() == 0) {
the_geom.setSRID(4326);
}
try {
return (MultiPolygon) the_geom;
} catch (ClassCastException e) {
throw new ParseException("WKT val is a " + the_geom.getClass().getName());
}
}
Example 75
Project: gvnix-master File: QuerydslUtilsBeanGeoImpl.java View source code |
@Override public <T> BooleanBuilder createPredicateByAnd(PathBuilder<T> entity, Map<String, Object> searchArgs) { BooleanBuilder predicate = super.createPredicateByAnd(entity, searchArgs); if (searchArgs == null || searchArgs.isEmpty()) { return predicate; } // Build the predicate for (Entry<String, Object> entry : searchArgs.entrySet()) { String key = entry.getKey(); // searchArgs can contain dtt_bbox attribute if (key.equals(DatatablesUtilsBeanGeoImpl.BOUNDING_BOX_PARAM)) { // Getting bbox to Search String bBoxToSearch = ((String[]) entry.getValue())[0]; Geometry bBoxGeometry = null; try { bBoxGeometry = getConversionService().convert(bBoxToSearch, Geometry.class); } catch (Exception e) { try { bBoxGeometry = getConversionService().convert(String.format("POLYGON((%s))", bBoxToSearch), Geometry.class); } catch (Exception e1) { throw new RuntimeException(String.format("Error getting map Bounding Box on QuerydslUtils from string: '%s'", bBoxToSearch), e); } } // Getting fields to filter using bbox if (searchArgs.get(DatatablesUtilsBeanGeoImpl.BOUNDING_BOX_FIELDS_PARAM) != null && bBoxGeometry != null) { String bBoxFields = ((String[]) searchArgs.get(DatatablesUtilsBeanGeoImpl.BOUNDING_BOX_FIELDS_PARAM))[0]; String[] separatedFields = StringUtils.split(bBoxFields, ","); for (String field : separatedFields) { predicate.or(createIntersectsExpression(entity, field, bBoxGeometry)); } } } } return predicate; }
Example 76
Project: h2gis-master File: SpatialResultSetImpl.java View source code |
@Override public Geometry getGeometry(int columnIndex) throws SQLException { Object field = getObject(columnIndex); if (field == null) { return (Geometry) field; } if (field instanceof Geometry) { return (Geometry) field; } else { throw new SQLException("The column " + getMetaData().getColumnName(columnIndex) + " is not a Geometry"); } }
Example 77
Project: jgrasstools-master File: TestVectorTransformer.java View source code |
public void testVectorTransformer() throws Exception {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("test");
b.setCRS(DefaultGeographicCRS.WGS84);
b.add("the_geom", Point.class);
b.add("id", Integer.class);
DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
Point point = GeometryUtilities.gf().createPoint(new Coordinate(0, 0));
Object[] values = new Object[] { point, 1 };
builder.addAll(values);
SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
newCollection.add(feature);
OmsVectorTransformer transformer = new OmsVectorTransformer();
transformer.inVector = newCollection;
transformer.pTransX = 1.0;
transformer.pTransY = -1.0;
transformer.process();
SimpleFeatureCollection outFeatures = transformer.outVector;
Geometry g = FeatureUtilities.featureCollectionToGeometriesList(outFeatures, false, null).get(0);
Coordinate coord = g.getCoordinate();
assertEquals(coord.x, 1.0, 0.00001);
assertEquals(coord.y, -1.0, 0.00001);
}
Example 78
Project: josm-conflation-plugin-master File: SymDiffMatcher.java View source code |
/** * The score is a linear function of the symmetric difference: 1 if the shapes perfectly * overlap; 0 if the shapes do not overlap at all. * @param target the feature to match * @param candidate the feature to compare with the target * @return candidates with a score greater than 0 (typically all the candidates). */ public double match(Geometry target, Geometry candidate) { Geometry targetGeom = (Geometry) target.clone(); Geometry candidateGeom = (Geometry) candidate.clone(); if (targetGeom.isEmpty() || candidateGeom.isEmpty()) { //avoid div by 0 in centre-of-mass calc [Jon Aquino] return 0; } return MatcherUtil.toScoreFromSymDiffArea(targetGeom.getArea(), candidateGeom.getArea(), targetGeom.symDifference(candidateGeom).getArea()); }
Example 79
Project: mapfish-print-master File: AbstractFeatureSourceLayerPlugin.java View source code |
@Override
public Style load(final MfClientHttpRequestFactory requestFactory, final FeatureSource featureSource) {
if (featureSource == null) {
throw new IllegalArgumentException("Feature source cannot be null");
}
String geomType = Geometry.class.getSimpleName().toLowerCase();
if (featureSource.getSchema() != null) {
geomType = featureSource.getSchema().getGeometryDescriptor().getType().getBinding().getSimpleName();
}
String styleRef = styleString;
if (styleRef == null) {
styleRef = geomType;
}
final StyleParser styleParser = AbstractFeatureSourceLayerPlugin.this.parser;
return template.getStyle(styleRef).or(styleParser.loadStyle(template.getConfiguration(), requestFactory, styleRef)).or(template.getConfiguration().getDefaultStyle(geomType));
}
Example 80
Project: mobilitytestbed-master File: InterpolableTimeKmlItemBuilder.java View source code |
@Override
public KmlItem buildKmlItem() throws SQLException {
logger.info("Preparing visualizations: " + this.getClass().getSimpleName());
TimeKmlItem kmlItem;
if (interpolated)
kmlItem = getInterpolatedTimeKmlItem();
else
kmlItem = getNonInterpolatedTimeKmlItem();
String sql = "SELECT " + " * FROM " + schemaName + "." + tableName + " " + whereClause + " ORDER BY from_time";
ResultSet resultSet = connection.executeQueryWithFetchSize(sql, 10000);
while (resultSet.next()) {
String id = getRecordId(resultSet);
Geometry geom = getGeometry(resultSet, "geom");
Timestamp timestamp = resultSet.getTimestamp("from_time");
kmlItem.addTimeGeometry(id, convertJTSCoordinatesToKmlCoordinates(geom.getCoordinates()), timestamp.getTime(), descriptionFactory.createDescription(resultSet));
}
//logger.info(this.getClass().getSimpleName()+" finishes building.");
return kmlItem;
}
Example 81
Project: onebusaway-application-modules-master File: BoundingBoxController.java View source code |
@RequestMapping()
public ModelAndView index() {
GeometryFactory gf = new GeometryFactory();
List<Polygon> polygons = new ArrayList<Polygon>();
Map<String, CoordinateBounds> agencies = _agencyService.getAgencyIdsAndCoverageAreas();
for (CoordinateBounds cb : agencies.values()) {
Envelope e = new Envelope(cb.getMinLon(), cb.getMaxLon(), cb.getMinLat(), cb.getMaxLat());
Polygon p = (Polygon) gf.toGeometry(e);
polygons.add(p);
}
MultiPolygon mp = gf.createMultiPolygon(polygons.toArray(new Polygon[0]));
Geometry hull = mp.convexHull();
Envelope env = hull.getEnvelopeInternal();
ModelAndView mv = new ModelAndView("bounding-box.jspx");
mv.addObject("minY", env.getMinY());
mv.addObject("minX", env.getMinX());
mv.addObject("maxY", env.getMaxY());
mv.addObject("maxX", env.getMaxX());
mv.addObject("hullWKT", hull.toText());
return mv;
}
Example 82
Project: OSM2World-master File: CAGUtil.java View source code |
/** * takes a polygon outline, "subtracts" a collection of other polygon outlines, * and returns a collection of polygons that covers the difference area. * * The result polygons should cover the area that was * within the original polygon (excluding its holes), * but not within a subtracted polygon. * * @return * polygons without self-intersections, but maybe with holes */ public static final Collection<PolygonWithHolesXZ> subtractPolygons(SimplePolygonXZ basePolygon, List<? extends SimplePolygonXZ> subtractPolygons) { List<Geometry> remainingGeometry = Collections.singletonList((Geometry) polygonXZToJTSPolygon(basePolygon)); for (SimplePolygonXZ subtractPolygon : subtractPolygons) { Polygon jtsSubtractPolygon = polygonXZToJTSPolygon(subtractPolygon); if (!jtsSubtractPolygon.isValid()) continue; List<Geometry> newRemainingGeometry = new ArrayList<Geometry>(1); for (Geometry g : remainingGeometry) { Geometry newG = g.difference(jtsSubtractPolygon); if (newG instanceof GeometryCollection) { for (int i = 0; i < ((GeometryCollection) newG).getNumGeometries(); i++) { newRemainingGeometry.add(((GeometryCollection) newG).getGeometryN(i)); } } else { newRemainingGeometry.add(newG); } } remainingGeometry = newRemainingGeometry; } Collection<PolygonWithHolesXZ> result = new ArrayList<PolygonWithHolesXZ>(); for (Geometry g : remainingGeometry) { result.addAll(polygonsXZFromJTSGeometry(g)); } return result; }
Example 83
Project: snap-desktop-master File: CorrelativeFieldSelectorTest.java View source code |
@Test
public void testUpdatePointDataSource() throws Exception {
final BindingContext bindingContext = new BindingContext();
bindingContext.getPropertySet().addProperties(Property.create("pointDataSource", VectorDataNode.class));
bindingContext.getPropertySet().addProperties(Property.create("dataField", AttributeDescriptor.class));
final CorrelativeFieldSelector correlativeFieldSelector = new CorrelativeFieldSelector(bindingContext);
final Product product = new Product("name", "type", 10, 10);
product.getVectorDataGroup().add(new VectorDataNode("a", createFeatureType(Geometry.class)));
product.getVectorDataGroup().add(new VectorDataNode("b", createFeatureType(Point.class)));
assertEquals(0, correlativeFieldSelector.pointDataSourceList.getItemCount());
assertEquals(0, correlativeFieldSelector.dataFieldList.getItemCount());
correlativeFieldSelector.updatePointDataSource(product);
assertEquals(3, correlativeFieldSelector.pointDataSourceList.getItemCount());
assertEquals(0, correlativeFieldSelector.dataFieldList.getItemCount());
correlativeFieldSelector.pointDataSourceProperty.setValue(product.getVectorDataGroup().get("b"));
assertEquals(3, correlativeFieldSelector.dataFieldList.getItemCount());
}
Example 84
Project: SOS-master File: OmObservationTest.java View source code |
@Test public final void should_have_SpatialFilteringProfileParameter() throws OwsExceptionReport { OmObservation omObservation = new OmObservation(); NamedValue<Geometry> namedValue = new NamedValue<Geometry>(); namedValue.setName(new ReferenceType(OmConstants.PARAM_NAME_SAMPLING_GEOMETRY)); namedValue.setValue(new GeometryValue(JTSHelper.createGeometryFromWKT("POINT (34.5 76.4)", Constants.EPSG_WGS84))); // test no parameter is set assertFalse(omObservation.isSetParameter()); assertFalse(omObservation.isSetSpatialFilteringProfileParameter()); omObservation.addParameter(namedValue); // test with set SpatialFilteringProfile parameter assertTrue(omObservation.isSetParameter()); assertTrue(omObservation.isSetSpatialFilteringProfileParameter()); assertThat(omObservation.getSpatialFilteringProfileParameter(), is(equalTo(namedValue))); }
Example 85
Project: sql-layer-master File: GeoWKT.java View source code |
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends ValueSource> inputs, ValueTarget output) {
String wkt = inputs.get(0).getString();
WKTReader reader = (WKTReader) context.preptimeObjectAt(READER_CONTEXT_POS);
try {
Geometry geometry = reader.read(wkt);
output.putObject(geometry);
} catch (ParseException e) {
throw new InvalidSpatialObjectException(e.getMessage());
}
}
Example 86
Project: street-master File: ElementGeometry.java View source code |
private LatLon findCenterPoint() {
try {
Geometry geom = JTSConst.toGeometry(this);
if (!geom.isValid())
return null;
if (geom instanceof Polygonal) {
return JTSConst.toLatLon(geom.getInteriorPoint());
} else if (geom instanceof Lineal) {
LengthIndexedLine lil = new LengthIndexedLine(geom);
return JTSConst.toLatLon(lil.extractPoint(geom.getLength() / 2.0));
}
} catch (IllegalArgumentException e) {
return null;
}
return null;
}
Example 87
Project: StreetComplete-master File: ElementGeometry.java View source code |
private LatLon findCenterPoint() {
try {
Geometry geom = JTSConst.toGeometry(this);
if (!geom.isValid())
return null;
if (geom instanceof Polygonal) {
return JTSConst.toLatLon(geom.getInteriorPoint());
} else if (geom instanceof Lineal) {
LengthIndexedLine lil = new LengthIndexedLine(geom);
return JTSConst.toLatLon(lil.extractPoint(geom.getLength() / 2.0));
}
} catch (IllegalArgumentException e) {
return null;
}
return null;
}
Example 88
Project: wheelmap-android-master File: SmallestSurroundingRectangle.java View source code |
public static Polygon get(Geometry geom, GeometryFactory gf) { Geometry hull_ = (new ConvexHull(geom)).getConvexHull(); if (!(hull_ instanceof Polygon)) return null; Polygon convHull = (Polygon) hull_; Coordinate c = geom.getCentroid().getCoordinate(); Coordinate[] coords = convHull.getExteriorRing().getCoordinates(); double minArea = Double.MAX_VALUE, minAngle = 0.0; Polygon ssr = null; Coordinate ci = coords[0], cii; for (int i = 0; i < coords.length - 1; i++) { cii = coords[i + 1]; double angle = Math.atan2(cii.y - ci.y, cii.x - ci.x); Polygon rect = (Polygon) Rotation.get(convHull, c, -1.0 * angle, gf).getEnvelope(); double area = rect.getArea(); if (area < minArea) { minArea = area; ssr = rect; minAngle = angle; } ci = cii; } return Rotation.get(ssr, c, minAngle, gf); }
Example 89
Project: WPS-master File: GTBinZippedWKT64Parser.java View source code |
/** * @throws RuntimeException * if an error occurs while writing the stream to disk or * unzipping the written file * @see org.n52.wps.io.IParser#parse(java.io.InputStream) */ @Override public GTVectorDataBinding parse(InputStream stream, String mimeType, String schema) { try { String fileName = "tempfile" + UUID.randomUUID() + ".zip"; String tmpDirPath = System.getProperty("java.io.tmpdir"); File tempFile = new File(tmpDirPath + File.separatorChar + fileName); // mark tempFile for final delete finalizeFiles.add(tempFile); try { FileOutputStream outputStream = new FileOutputStream(tempFile); byte buf[] = new byte[4096]; int len; while ((len = stream.read(buf)) > 0) { outputStream.write(buf, 0, len); } outputStream.close(); stream.close(); } catch (FileNotFoundException e) { System.gc(); LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } catch (IOException e) { LOGGER.error(e.getMessage(), e); System.gc(); throw new RuntimeException(e); } // mark for final delete finalizeFiles.add(tempFile); stream.close(); List<File> wktFiles = IOUtils.unzip(tempFile, "wkt"); // mark for final delete finalizeFiles.addAll(wktFiles); if (wktFiles == null || wktFiles.size() == 0) { throw new RuntimeException("Cannot find a shapefile inside the zipped file."); } //set namespace namespace List<Geometry> geometries = new ArrayList<Geometry>(); //please not that only 1 geometry is returned. If multiple geometries are included, perhaps use the read(String wktstring) method for (int i = 0; i < wktFiles.size(); i++) { File wktFile = wktFiles.get(i); Reader fileReader = new FileReader(wktFile); WKTReader2 wktReader = new WKTReader2(); com.vividsolutions.jts.geom.Geometry geometry = wktReader.read(fileReader); geometries.add(geometry); } CoordinateReferenceSystem coordinateReferenceSystem = CRS.decode("EPSG:4326"); SimpleFeatureCollection inputFeatureCollection = createFeatureCollection(geometries, coordinateReferenceSystem); return new GTVectorDataBinding(inputFeatureCollection); } catch (IOException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException("An error has occurred while accessing provided data", e); } catch (ParseException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException("An error has occurred while accessing provided data", e); } catch (NoSuchAuthorityCodeException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException("An error has occurred while accessing provided data", e); } catch (FactoryException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException("An error has occurred while accessing provided data", e); } }
Example 90
Project: geolatte-common-master File: EntityClassReaderTest.java View source code |
@Test public void NoShapeDoubleShapeTest() { PointSequence points = PointCollectionFactory.create(new double[] { 8, 9, 9, 10, 10, 11 }, DimensionalFlag.d2D, CrsId.UNDEFINED); LineString shape2 = new LineString(points); points = PointCollectionFactory.create(new double[] { 5, 6, 6, 7, 7, 8 }, DimensionalFlag.d2D, CrsId.UNDEFINED); LineString shape = new LineString(points); Object noShape = new TestFeatureNoShape("Antwerpen", 128, new String[] { "Belgium", "Flanders" }, 5, "sub", "subsub"); Object doubleShape = new TestFeatureDoubleShape("Antwerpen", 128, new String[] { "Belgium", "Flanders" }, shape, 5, shape2, "sub"); reader = EntityClassReader.getClassReaderFor(noShape.getClass()); try { Geometry test = reader.getGeometry(noShape); Assert.assertNull(test); } catch (InvalidObjectReaderException e) { Assert.fail("No Exception should be thrown when no one geometry is present"); } reader = EntityClassReader.getClassReaderFor(doubleShape.getClass()); try { Geometry geom = reader.getGeometry(doubleShape); Assert.assertTrue(geom == shape2 || geom == shape); } catch (InvalidObjectReaderException e) { Assert.fail("No Exception should be thrown when more than one geometry is present"); } }
Example 91
Project: archive-ddf-spatial-master File: GmlGeometryConverter.java View source code |
@Override public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { Geometry geometry = (Geometry) value; GMLWriter gmlWriter = new GMLWriter(); String gmlXml = gmlWriter.write(geometry); // Copy the GML XML into the writer XmlPullParser parser = null; try { parser = XppFactory.createDefaultParser(); new HierarchicalStreamCopier().copy(new XppReader(new StringReader(gmlXml), parser), writer); } catch (XmlPullParserException e) { LOGGER.warn(ERROR_SERIALIZING_MSG, e); } }
Example 92
Project: DataHubSystem-master File: NominatimGeocoderTest.java View source code |
/** * Test the getBoundariesWKT() operation of the NominatimGeocoder. * The test consists in a call with "france" as search query that shall * contains paris, noumea, and shall not contains berlin. * @throws ParseException */ @Test public void getBoundariesWKTFrance() throws ParseException { XmlDocument document = getDocument("france.xml"); String wkt_france = this.geocoder.computeWKT(document); Assert.assertNotNull(wkt_france, "France geometry not found."); document = getDocument("paris.xml"); String wkt_paris = this.geocoder.computeWKT(document); Assert.assertNotNull(wkt_paris, "Paris geometry not found."); WKTReader reader = new WKTReader(); Geometry france = reader.read(wkt_france); Geometry paris = reader.read(wkt_paris); // Test paris place is inside "France" Assert.assertTrue(france.contains(paris), "Paris geometry is not inside france"); // Check Noumea france territory in also inside france document = getDocument("noumea.xml"); String wkt_noumea = this.geocoder.computeWKT(document); Assert.assertNotNull(wkt_noumea, "Nouméa geometry not found."); Geometry noumea = reader.read(wkt_noumea); Assert.assertTrue(france.contains(noumea), "Nouméa geometry is not inside france"); // Check berlin is outside france document = getDocument("berlin.xml"); String wkt_berlin = this.geocoder.computeWKT(document); Assert.assertNotNull(wkt_berlin, "Berlin geometry not found."); Geometry berlin = reader.read(wkt_berlin); Assert.assertFalse(france.contains(berlin), "Berlin geometry is found inside france"); }
Example 93
Project: deegree-securityproxy-master File: GeometryRetrieverImpl.java View source code |
private Geometry retrieveGeometryForLayer(List<GeometryFilterInfo> geometryFilterInfos, String layerName) throws ParseException {
for (GeometryFilterInfo wcsGeometryFilterInfo : geometryFilterInfos) {
if (layerName.equals(wcsGeometryFilterInfo.getLayerName())) {
String geometryString = wcsGeometryFilterInfo.getGeometryString();
if (geometryString != null)
return parseGeometry(geometryString);
}
}
return null;
}
Example 94
Project: elassandra-master File: MultiLineStringBuilder.java View source code |
@Override
public Shape build() {
final Geometry geometry;
if (wrapdateline) {
ArrayList<LineString> parts = new ArrayList<>();
for (BaseLineStringBuilder<?> line : lines) {
BaseLineStringBuilder.decompose(FACTORY, line.coordinates(false), parts);
}
if (parts.size() == 1) {
geometry = parts.get(0);
} else {
LineString[] lineStrings = parts.toArray(new LineString[parts.size()]);
geometry = FACTORY.createMultiLineString(lineStrings);
}
} else {
LineString[] lineStrings = new LineString[lines.size()];
Iterator<BaseLineStringBuilder<?>> iterator = lines.iterator();
for (int i = 0; iterator.hasNext(); i++) {
lineStrings[i] = FACTORY.createLineString(iterator.next().coordinates(false));
}
geometry = FACTORY.createMultiLineString(lineStrings);
}
return jtsGeometry(geometry);
}
Example 95
Project: elasticgeo-master File: ElasticFeatureTypeBuilder.java View source code |
@Override
public SimpleFeatureType buildFeatureType() {
if (attributes != null) {
String defaultGeometryName = null;
for (ElasticAttribute attribute : attributes) {
if (attribute.isUse()) {
final String attributeName;
if (attribute.getUseShortName()) {
attributeName = attribute.getShortName();
} else {
attributeName = attribute.getName();
}
AttributeDescriptor att = null;
if (Geometry.class.isAssignableFrom(attribute.getType())) {
final Integer srid = attribute.getSrid();
try {
if (srid != null) {
attributeBuilder.setCRS(CRS.decode("EPSG:" + srid));
attributeBuilder.setName(attributeName);
attributeBuilder.setBinding(attribute.getType());
att = attributeBuilder.buildDescriptor(attributeName, attributeBuilder.buildGeometryType());
final ElasticGeometryType geometryType = attribute.getGeometryType();
att.getUserData().put(GEOMETRY_TYPE, geometryType);
if (attribute.isDefaultGeometry() != null && attribute.isDefaultGeometry()) {
defaultGeometryName = attributeName;
}
}
} catch (Exception e) {
String msg = "Error occured determing srid for " + attribute.getName();
LOGGER.log(Level.WARNING, msg, e);
}
} else {
attributeBuilder.setName(attributeName);
attributeBuilder.setBinding(attribute.getType());
att = attributeBuilder.buildDescriptor(attributeName, attributeBuilder.buildType());
}
if (att != null && attribute.getDateFormat() != null) {
att.getUserData().put(DATE_FORMAT, attribute.getDateFormat());
}
if (att != null) {
att.getUserData().put(FULL_NAME, attribute.getName());
att.getUserData().put(ANALYZED, attribute.getAnalyzed());
att.getUserData().put(NESTED, attribute.isNested());
add(att);
}
}
}
if (defaultGeometryName != null) {
setDefaultGeometry(defaultGeometryName);
}
}
return super.buildFeatureType();
}
Example 96
Project: elasticsearch-master File: MultiLineStringBuilder.java View source code |
@Override
public Shape build() {
final Geometry geometry;
if (wrapdateline) {
ArrayList<LineString> parts = new ArrayList<>();
for (LineStringBuilder line : lines) {
LineStringBuilder.decompose(FACTORY, line.coordinates(false), parts);
}
if (parts.size() == 1) {
geometry = parts.get(0);
} else {
LineString[] lineStrings = parts.toArray(new LineString[parts.size()]);
geometry = FACTORY.createMultiLineString(lineStrings);
}
} else {
LineString[] lineStrings = new LineString[lines.size()];
Iterator<LineStringBuilder> iterator = lines.iterator();
for (int i = 0; iterator.hasNext(); i++) {
lineStrings[i] = FACTORY.createLineString(iterator.next().coordinates(false));
}
geometry = FACTORY.createMultiLineString(lineStrings);
}
return jtsGeometry(geometry);
}
Example 97
Project: geosummly-master File: GeoJSONReader.java View source code |
/**
* Decode a geojson file for the sampling state
*/
public ArrayList<BoundingBox> decodeForSampling(String file) throws IOException, JSONException {
MfGeoFactory mfFactory = new MfGeoFactory() {
public MfFeature createFeature(String id, MfGeometry geometry, JSONObject properties) {
return new SamplingFeatureTemplate(id, geometry, properties);
}
};
MfGeoJSONReader reader = new MfGeoJSONReader(mfFactory);
ArrayList<BoundingBox> data = new ArrayList<BoundingBox>();
File f = new File(file);
InputStream in = new FileInputStream(f);
String str = IOUtils.toString(in);
in.close();
//decode geojson file given as a String
MfGeo result = reader.decode(str);
MfFeatureCollection collection = (MfFeatureCollection) result;
//all the geojson features
ArrayList<MfFeature> coll = (ArrayList<MfFeature>) collection.getCollection();
SamplingFeatureTemplate feature;
MfGeometry featureGeometry;
Geometry jts;
Polygon polygon;
double north;
double east;
double south;
double west;
BoundingBox b;
for (MfFeature mf : coll) {
feature = (SamplingFeatureTemplate) mf;
//get the feature geometry
featureGeometry = feature.getMfGeometry();
jts = featureGeometry.getInternalGeometry();
//feature geometry is a polygon
polygon = (Polygon) jts;
//get the bbox coordinates
north = polygon.getExteriorRing().getPointN(0).getCoordinate().y;
east = polygon.getExteriorRing().getPointN(1).getCoordinate().x;
south = polygon.getExteriorRing().getPointN(2).getCoordinate().y;
west = polygon.getExteriorRing().getPointN(3).getCoordinate().x;
b = new BoundingBox(north, east, south, west);
data.add(b);
}
//Set the matrix indices
//First row and col indices are equal to 1
int size = (int) Math.sqrt(data.size());
int i = 1;
int j = 1;
for (BoundingBox box : data) {
box.setRow(i);
box.setColumn(j);
j++;
if (//row complete, continue with the next row
j > size) {
i++;
j = 1;
}
}
return data;
}
Example 98
Project: geowebcache-master File: RasterMaskTestUtils.java View source code |
public static GeometryRasterMaskBuilder buildSampleFilterMatrix(final TileLayer layer, final String gridsetId, final int maxMaskLevel) throws Exception { final Geometry entries[] = createSampleEntries(); final GridSubset gridSubset = layer.getGridSubset(layer.getGridSubsets().iterator().next()); final int[] metaTilingFactors = layer.getMetaTilingFactors(); GeometryRasterMaskBuilder matrix = new GeometryRasterMaskBuilder(gridSubset, metaTilingFactors, maxMaskLevel); try { for (Geometry geom : entries) { matrix.setMasksForGeometry(geom); } } finally { matrix.disposeGraphics(); } logImages(new File("target"), matrix); return matrix; }
Example 99
Project: gt-jdbc-monetdb-master File: MonetDBFilterToSQL.java View source code |
@Override protected void visitLiteralGeometry(Literal expression) throws IOException { // evaluate the literal and store it for later Geometry geom = (Geometry) evaluateLiteral(expression, Geometry.class); if (geom instanceof LinearRing) { //postgis does not handle linear rings, convert to just a line string geom = geom.getFactory().createLineString(((LinearRing) geom).getCoordinateSequence()); } out.write("GeomFromText('"); out.write(geom.toText()); if (currentSRID == null && currentGeometry != null) { // if we don't know at all, use the srid of the geometry we're comparing against // (much slower since that has to be extracted record by record as opposed to // being a constant) out.write("', SRID(\"" + currentGeometry.getLocalName() + "\"))"); } else { out.write("', " + currentSRID + ")"); } }
Example 100
Project: hibernate-demos-master File: SpatialDemo.java View source code |
@SuppressWarnings("unchecked")
public List<Project> getProjects(String wktFilter) throws Exception {
final Session s = openSession();
s.getTransaction().begin();
final Geometry filter = wktToGeometry(wktFilter);
final Query query = s.createQuery("FROM Project p WHERE WITHIN(p.location, :filter) = TRUE");
query.setParameter("filter", filter);
final List<Project> projects = query.list();
s.getTransaction().commit();
s.close();
return projects;
}
Example 101
Project: jai-ext-master File: VectorBinarizeRIF.java View source code |
/** * Creates a new instance of VectorBinarizeOpImage in the rendered layer. * * @param paramBlock parameter block with parameters minx, miny, width height, geometry and coordtype * * @param renderHints optional rendering hints which may be used to pass an {@code ImageLayout} object containing a {@code SampleModel} to use * when creating destination tiles */ public RenderedImage create(ParameterBlock paramBlock, RenderingHints renderHints) { int minx = paramBlock.getIntParameter(VectorBinarizeDescriptor.MINX_ARG); int miny = paramBlock.getIntParameter(VectorBinarizeDescriptor.MINY_ARG); int width = paramBlock.getIntParameter(VectorBinarizeDescriptor.WIDTH_ARG); int height = paramBlock.getIntParameter(VectorBinarizeDescriptor.HEIGHT_ARG); Object obj = paramBlock.getObjectParameter(VectorBinarizeDescriptor.GEOM_ARG); PreparedGeometry pg = null; if (obj instanceof Polygonal) { // defensively copy the input Geometry Geometry g = (Geometry) ((Geometry) obj).clone(); pg = PreparedGeometryFactory.prepare(g); } else if (obj instanceof PreparedGeometry) { pg = (PreparedGeometry) obj; } else { throw new IllegalArgumentException("The geometry must be a JTS polygon or multipolygon"); } // get the tile size from the image layout Dimension tileSize = null; if (renderHints != null && renderHints.containsKey(JAI.KEY_IMAGE_LAYOUT)) { ImageLayout il = (ImageLayout) renderHints.get(JAI.KEY_IMAGE_LAYOUT); if (il != null) { tileSize = new Dimension(il.getTileWidth(null), il.getTileHeight(null)); } } if (tileSize == null) { tileSize = JAI.getDefaultTileSize(); } // sample model wise we only build bw images SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileSize.width, tileSize.height, 1); boolean antiAliasing = VectorBinarizeOpImage.DEFAULT_ANTIALIASING; Object antiAlias = paramBlock.getObjectParameter(VectorBinarizeDescriptor.ANTIALIASING_ARG); if (antiAlias != null && antiAlias instanceof Boolean) { antiAliasing = ((Boolean) antiAlias).booleanValue(); } return new VectorBinarizeOpImage(sm, renderHints, minx, miny, width, height, pg, antiAliasing); }