下面列出了org.json.simple.JSONAware#com.vividsolutions.jts.geom.LineString 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void dtoEmptyToJts() throws GeomajasException {
// Test DTO Point to JTS:
LineString ls = (LineString) converter.toInternal(createDtoEmpty(Geometry.LINE_STRING));
Assert.assertTrue(ls.isEmpty());
LinearRing lr = (LinearRing) converter.toInternal(createDtoEmpty(Geometry.LINEAR_RING));
Assert.assertTrue(lr.isEmpty());
MultiLineString mls = (MultiLineString) converter.toInternal(createDtoEmpty(Geometry.MULTI_LINE_STRING));
Assert.assertTrue(mls.isEmpty());
MultiPoint mp = (MultiPoint) converter.toInternal(createDtoEmpty(Geometry.MULTI_POINT));
Assert.assertTrue(mp.isEmpty());
MultiPolygon mpo = (MultiPolygon) converter.toInternal(createDtoEmpty(Geometry.MULTI_POLYGON));
Assert.assertTrue(mpo.isEmpty());
Point p = (Point) converter.toInternal(createDtoEmpty(Geometry.POINT));
Assert.assertTrue(p.isEmpty());
Polygon po = (Polygon) converter.toInternal(createDtoEmpty(Geometry.POLYGON));
Assert.assertTrue(po.isEmpty());
}
/**
* 生成KPolygon
* @param lineString
* @return
*/
public KPolygon makeKPolygonFrom(com.vividsolutions.jts.geom.LineString lineString) {
CoordinateSequence coordinateSequence = lineString.getCoordinateSequence();
ArrayList<Vector3> points = new ArrayList<>();
// The loop stops at the second-last coord since the last coord will be
// the same as the start coord.
Vector3 lastAddedPoint = null;
for (int i = 0; i < coordinateSequence.size() - 1; i++) {
Coordinate coord = coordinateSequence.getCoordinate(i);
Vector3 p = new Vector3((float)coord.x, (float)coord.z, (float)coord.y);
if (lastAddedPoint != null && p.x == lastAddedPoint.x && p.z == lastAddedPoint.z) {
// Don't add the point since it's the same as the last one
continue;
} else {
points.add(p);
lastAddedPoint = p;
}
}
if (points.size() < 3) {
return null;
}
KPolygon polygon = new KPolygon(points);
return polygon;
}
@Override
public Shape build() {
Coordinate[] coordinates = points.toArray(new Coordinate[points.size()]);
Geometry geometry;
if(wrapdateline) {
ArrayList<LineString> strings = decompose(FACTORY, coordinates, new ArrayList<LineString>());
if(strings.size() == 1) {
geometry = strings.get(0);
} else {
LineString[] linestrings = strings.toArray(new LineString[strings.size()]);
geometry = FACTORY.createMultiLineString(linestrings);
}
} else {
geometry = FACTORY.createLineString(coordinates);
}
return jtsGeometry(geometry);
}
/**
* Initialise.
*/
private static void initialise()
{
List<Class<?> > doubleList = new ArrayList<Class<?> >(Arrays.asList(Integer.class, Long.class, Double.class, Float.class));
List<Class<?> > integerList = new ArrayList<Class<?> >(Arrays.asList(Integer.class, Long.class));
List<Class<?> > stringList = new ArrayList<Class<?> >(Arrays.asList(String.class));
List<Class<?> > geometryList = new ArrayList<Class<?> >(Arrays.asList(Point.class, LineString.class, Polygon.class, MultiPolygon.class, MultiPoint.class, MultiLineString.class));
allowedClassTypeMap.put(String.class, stringList);
allowedClassTypeMap.put(Double.class, doubleList);
allowedClassTypeMap.put(Float.class, doubleList);
allowedClassTypeMap.put(Integer.class, integerList);
allowedClassTypeMap.put(Long.class, integerList);
allowedClassTypeMap.put(Geometry.class, geometryList);
List<Class<?> > objectList = new ArrayList<Class<?>>();
objectList.addAll(doubleList);
objectList.addAll(integerList);
objectList.addAll(stringList);
objectList.addAll(geometryList);
allowedClassTypeMap.put(Object.class, objectList);
}
@Override
public GamaShape getExteriorRing(final IScope scope) {
// WARNING Only in 2D
Geometry result = getInnerGeometry();
if (result instanceof Polygon) {
result = ((Polygon) result).getExteriorRing();
} else
if (result instanceof MultiPolygon) {
final MultiPolygon mp = (MultiPolygon) result;
final LineString lines[] = new LineString[mp.getNumGeometries()];
for (int i = 0; i < mp.getNumGeometries(); i++) {
lines[i] = ((Polygon) mp.getGeometryN(i)).getExteriorRing();
}
result = GEOMETRY_FACTORY.createMultiLineString(lines);
}
return new GamaShape(result);
}
protected double zVal(final GamaPoint point, final IShape edge) {
double z = 0.0;
final int nbSp = getPointsOf(edge).length;
final Coordinate[] temp = new Coordinate[2];
final Point pointGeom = (Point) point.getInnerGeometry();
double distanceS = Double.MAX_VALUE;
final GamaPoint[] edgePoints = GeometryUtils.getPointsOf(edge);
for (int i = 0; i < nbSp - 1; i++) {
temp[0] = edgePoints[i];
temp[1] = edgePoints[i + 1];
final LineString segment = GeometryUtils.GEOMETRY_FACTORY.createLineString(temp);
final double distS = segment.distance(pointGeom);
if (distS < distanceS) {
distanceS = distS;
final GamaPoint pt0 = new GamaPoint(temp[0]);
final GamaPoint pt1 = new GamaPoint(temp[1]);
z = pt0.z + (pt1.z - pt0.z) * point.distance(pt0) / segment.getLength();
}
}
return z;
}
public static Coordinate[] extractPoints(final IShape triangle1, final IShape triangle2) {
final Coordinate[] coords = triangle1.getInnerGeometry().getCoordinates();
final Coordinate[] c1 = { coords[0], coords[1] };
final Coordinate[] c2 = { coords[1], coords[2] };
final Coordinate[] c3 = { coords[2], coords[3] };
final LineString l1 = GEOMETRY_FACTORY.createLineString(c1);
final LineString l2 = GEOMETRY_FACTORY.createLineString(c2);
final LineString l3 = GEOMETRY_FACTORY.createLineString(c3);
final Coordinate[] pts = new Coordinate[3];
if (nbCommonPoints(l1, triangle2.getInnerGeometry()) == 2) {
pts[1] = l1.getCentroid().getCoordinate();
} else if (nbCommonPoints(l2, triangle2.getInnerGeometry()) == 2) {
pts[1] = l2.getCentroid().getCoordinate();
} else if (nbCommonPoints(l3, triangle2.getInnerGeometry()) == 2) {
pts[1] = l3.getCentroid().getCoordinate();
}
pts[0] = triangle1.getCentroid();
pts[2] = triangle2.getCentroid();
return pts;
}
/**
* Rough conversion from geometry to GML using a template.
* @param geo base Geometry gets delegated
* @return String gml encoding of the gemoetry
*/
private static String geoToGmlRough(final Geometry geo) {
final Geometries theType = org.geotools.geometry.jts.Geometries.get(geo);
switch (theType) {
case POINT:
return geoToGml((Point)geo);
case LINESTRING:
return geoToGml((LineString)geo);
case POLYGON:
return geoToGml((Polygon)geo);
case MULTIPOINT:
case MULTILINESTRING:
case MULTIPOLYGON:
default:
throw new Error("No code to convert to GML for this type: "+theType);
}
}
/**
* Rough conversion from geometry to GML using a template.
* @param geo base Geometry gets delegated
* @return String gml encoding of the gemoetry
*/
private static String geoToGmlRough(final Geometry geo) {
final Geometries theType = org.geotools.geometry.jts.Geometries.get(geo);
switch (theType) {
case POINT:
return geoToGml((Point)geo);
case LINESTRING:
return geoToGml((LineString)geo);
case POLYGON:
return geoToGml((Polygon)geo);
case MULTIPOINT:
case MULTILINESTRING:
case MULTIPOLYGON:
default:
throw new Error("No code to convert to GML for this type: "+theType);
}
}
private void computeMinDistanceLineLine(LineString line0, LineString line1,
boolean flip) {
Coordinate[] coord0 = line0.getCoordinates();
Coordinate[] coord1 = line1.getCoordinates();
// brute force approach!
for (int i = 0; i < coord0.length - 1; i++) {
for (int j = 0; j < coord1.length - 1; j++) {
double dist = CGAlgorithms3D.distanceSegmentSegment(coord0[i],
coord0[i + 1], coord1[j], coord1[j + 1]);
if (dist < minDistance) {
minDistance = dist;
// TODO: compute closest pts in 3D
LineSegment seg0 = new LineSegment(coord0[i], coord0[i + 1]);
LineSegment seg1 = new LineSegment(coord1[j], coord1[j + 1]);
Coordinate[] closestPt = seg0.closestPoints(seg1);
updateDistance(dist,
new GeometryLocation(line0, i, closestPt[0]),
new GeometryLocation(line1, j, closestPt[1]),
flip
);
}
if (isDone) return;
}
}
}
private static void updateGeometry(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
session.beginTransaction();
TheData theData = session.get(TheData.class, 1L);
LineString geometry = geometryFactory.createLineString(new Coordinate[]{
new Coordinate(5,6),
new Coordinate(7,8),
new Coordinate(9,10)});
theData.setTheGeometry(geometry);
session.saveOrUpdate(theData);
session.getTransaction().commit();
session.close();
}
private void addOSMOpenWays(OSMDataSet ds) {
List<OSMWay> openWays = ds.getOpenWays();
for (OSMWay w : openWays) {
if (!w.isModified() && OSMWay.containsModifiedWay(w.getId())) {
continue;
}
// Don't render or index ways that do not have all of their referenced nodes.
if (w.incomplete()) {
continue;
}
List<OSMNode> nodes = w.getNodes();
Coordinate[] coords = coordArrayFromNodeList(nodes);
LineString line = geometryFactory.createLineString(coords);
w.setJTSGeom(line);
Envelope envelope = line.getEnvelopeInternal();
spatialIndex.insert(envelope, w);
}
}
private void writeGeometry(Geometry g, int level, StringBuffer buf) {
String attributes = "";
if (g instanceof Point) {
writePoint((Point) g, attributes, level, buf);
} else if (g instanceof LinearRing) {
writeLinearRing((LinearRing) g, attributes, true, level, buf);
} else if (g instanceof LineString) {
writeLineString((LineString) g, attributes, level, buf);
} else if (g instanceof Polygon) {
writePolygon((Polygon) g, attributes, level, buf);
} else if (g instanceof GeometryCollection) {
writeGeometryCollection((GeometryCollection) g, attributes, level, buf);
}
else
throw new IllegalArgumentException("Geometry type not supported: " + g.getGeometryType());
}
/**
* Computes a list of values for the points along a line by
* interpolating between values for the start and end point.
* The interpolation is
* based on the distance of each point along the line
* relative to the total line length.
*
* @param line the line to interpolate along
* @param start the start value
* @param end the end value
* @return the array of interpolated values
*/
public static double[] interpolate(LineString line, double start,
double end) {
start = Math.abs(start);
end = Math.abs(end);
double[] widths = new double[line.getNumPoints()];
widths[0] = start;
widths[widths.length - 1] = end;
double totalLen = line.getLength();
Coordinate[] pts = line.getCoordinates();
double currLen = 0;
for (int i = 1; i < widths.length; i++) {
double segLen = pts[i].distance(pts[i - 1]);
currLen += segLen;
double lenFrac = currLen / totalLen;
double delta = lenFrac * (end - start);
widths[i] = start + delta;
}
return widths;
}
/**
* Converts a <code>LineString</code> to <LineString Text> format, then
* appends it to the writer.
*
*@param lineString the <code>LineString</code> to process
*@param writer the output writer to append to
*/
private void appendLineStringText(LineString lineString, int level, boolean doIndent, Writer writer)
throws IOException
{
if (lineString.isEmpty()) {
writer.write("EMPTY");
}
else {
if (doIndent) indent(level, writer);
writer.write("(");
for (int i = 0; i < lineString.getNumPoints(); i++) {
if (i > 0) {
writer.write(", ");
if (coordsPerLine > 0
&& i % coordsPerLine == 0) {
indent(level + 1, writer);
}
}
appendCoordinate(lineString.getCoordinateN(i), writer);
}
writer.write(")");
}
}
/**
* Returns the GTYPE GEOM_TYPE code
* corresponding to the geometry type.
*
* @see OraGeom.GEOM_TYPE
*
* @param geom the geometry to compute the GEOM_TYPE for
* @return geom type code, if known, or UNKNOWN
*/
static int geomType(Geometry geom) {
if (geom == null) {
return OraGeom.GEOM_TYPE.UNKNOWN_GEOMETRY;
} else if (geom instanceof Point) {
return OraGeom.GEOM_TYPE.POINT;
} else if (geom instanceof LineString) {
return OraGeom.GEOM_TYPE.LINE;
} else if (geom instanceof Polygon) {
return OraGeom.GEOM_TYPE.POLYGON;
} else if (geom instanceof MultiPoint) {
return OraGeom.GEOM_TYPE.MULTIPOINT;
} else if (geom instanceof MultiLineString) {
return OraGeom.GEOM_TYPE.MULTILINE;
} else if (geom instanceof MultiPolygon) {
return OraGeom.GEOM_TYPE.MULTIPOLYGON;
} else if (geom instanceof GeometryCollection) {
return OraGeom.GEOM_TYPE.COLLECTION;
}
return OraGeom.GEOM_TYPE.UNKNOWN_GEOMETRY;
}
@Test
public void testConversion() {
// dto -> internal
for (LayerType layerType : LayerType.values()) {
if (layerType != LayerType.RASTER) {
Class<? extends Geometry> c = converterService.toInternal(layerType);
Assert.assertEquals(layerType.name(), c.getSimpleName().toUpperCase());
} else {
Assert.assertNull(converterService.toInternal(layerType));
}
}
// internal -> dto
Assert.assertEquals(LayerType.POINT, converterService.toDto(Point.class));
Assert.assertEquals(LayerType.MULTIPOINT, converterService.toDto(MultiPoint.class));
Assert.assertEquals(LayerType.LINESTRING, converterService.toDto(LineString.class));
Assert.assertEquals(LayerType.MULTILINESTRING, converterService.toDto(MultiLineString.class));
Assert.assertEquals(LayerType.POLYGON, converterService.toDto(Polygon.class));
Assert.assertEquals(LayerType.MULTIPOLYGON, converterService.toDto(MultiPolygon.class));
Assert.assertEquals(LayerType.GEOMETRY, converterService.toDto(Geometry.class));
}
public void testRawLineStringM2() throws Exception {
final GeometryFactory geometryFactory = new GeometryFactory();
final OraReader oraReader = new OraReader(geometryFactory);
// Geometry type is a 3-dimensional measured line.
final int gType = 3302;
// The 'line' is starting at ordinate offset 1.
final int[] elemInfo = new int[] {1, 2, 1};
final double[] ordinates = new double[] {1, 1, 20, 2, 2, 30};
// Made 'create' method package private to enable test.
final Geometry actual = oraReader.read(new OraGeom(gType, 0, elemInfo, ordinates));
// Preparing expected result.
final LineString expected =
geometryFactory.createLineString(new Coordinate[] {new Coordinate(1, 1), new Coordinate(2, 2)});
assertEquals(expected, actual);
}
/**
* Writes the body for a <code>MultiPolygon</code> object. MultiPolygons are
* encoded into SVG path elements. This function writes the different
* polygons in one d-attribute of an SVG path element, separated by an 'M'
* character. (in other words, it calls the super.writeBody for each
* polygon).
*
* @param o The <code>MultiPolygon</code> to be encoded.
*/
public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {
document.writeElement("vml:shape", asChild);
document.writeAttribute("fill-rule", "evenodd");
document.writeAttributeStart("path");
MultiPolygon mpoly = (MultiPolygon) o;
for (int i = 0; i < mpoly.getNumGeometries(); i++) {
Polygon poly = (Polygon) mpoly.getGeometryN(i);
LineString shell = poly.getExteriorRing();
int nHoles = poly.getNumInteriorRing();
document.writeClosedPathContent(shell.getCoordinates());
for (int j = 0; j < nHoles; j++) {
document.writeClosedPathContent(poly.getInteriorRingN(j).getCoordinates());
}
}
document.writeAttributeEnd();
}
/**
* Writes the object to the specified document, optionally creating a child
* element. The object in this case should be a polygon.
*
* @param o the object (of type Polygon).
* @param document the document to write to.
* @param asChild create child element if true.
* @throws RenderException
*/
public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {
document.writeElement("vml:shape", asChild);
document.writeAttributeStart("path");
Polygon poly = (Polygon) o;
LineString shell = poly.getExteriorRing();
int nHoles = poly.getNumInteriorRing();
document.writeClosedPathContent(shell.getCoordinates());
for (int j = 0; j < nHoles; j++) {
document.writeClosedPathContent(poly.getInteriorRingN(j).getCoordinates());
}
document.writeAttributeEnd();
}
/**
* Creates a MultiLineString.
*/
public static MultiLineString toMultiLineString(MultiLineStringCoordinates coords) {
if (coords == null) {
return null;
}
LineString[] lines = new LineString[coords.size()];
for (int i = 0; i < lines.length; i++) {
lines[i] = toLineString(coords.get(i));
}
return JTSHelper.factory.createMultiLineString(lines);
}
/**
* Creates a JTS Geometry from the provided GeoJSON geometry.
*/
@SuppressWarnings("unchecked")
public static <X extends Geometry> X toGeometry(com.here.xyz.models.geojson.implementation.Geometry geometry) {
if (geometry == null) {
return null;
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.Point) {
return (X) toPoint(((com.here.xyz.models.geojson.implementation.Point) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.MultiPoint) {
return (X) toMultiPoint(((com.here.xyz.models.geojson.implementation.MultiPoint) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.LineString) {
return (X) toLineString(((com.here.xyz.models.geojson.implementation.LineString) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.MultiLineString) {
return (X) toMultiLineString(((com.here.xyz.models.geojson.implementation.MultiLineString) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.Polygon) {
return (X) toPolygon(((com.here.xyz.models.geojson.implementation.Polygon) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.MultiPolygon) {
return (X) toMultiPolygon(((com.here.xyz.models.geojson.implementation.MultiPolygon) geometry).getCoordinates());
}
if (geometry instanceof com.here.xyz.models.geojson.implementation.GeometryCollection) {
return (X) toGeometryCollection(((com.here.xyz.models.geojson.implementation.GeometryCollection) geometry));
}
return null;
}
@SuppressWarnings("rawtypes")
private MultiLineString parseResponse(Object response) throws IOException {
List<LineString> lines = new ArrayList<LineString>();
String jsonString = responseToString(response);
JSONObject json = JSONObject.fromObject(jsonString);
if ("OK".equals(json.get("status"))) {
JSONArray routes = json.getJSONArray("routes");
JSONArray legs = routes.getJSONObject(0).getJSONArray("legs");
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
if (log.isDebugEnabled())
log.debug("Get route with " + steps.size() + " steps");
Iterator iter = steps.iterator();
while (iter.hasNext()) {
JSONObject step = (JSONObject) iter.next();
String polyline = step.getJSONObject("polyline").getString("points");
LineString line = decodePolyline(polyline);
lines.add(line);
}
}
return new MultiLineString(lines.toArray(new LineString[] {}), factory);
}
private void setLayerType(VectorLayerInfo info, GeometryDescriptor geoType) {
if (geoType.getType().getBinding() == Point.class) {
info.setLayerType(LayerType.POINT);
} else if (geoType.getType().getBinding() == MultiPoint.class) {
info.setLayerType(LayerType.MULTIPOINT);
} else if (geoType.getType().getBinding() == LineString.class) {
info.setLayerType(LayerType.LINESTRING);
} else if (geoType.getType().getBinding() == MultiLineString.class) {
info.setLayerType(LayerType.MULTILINESTRING);
} else if (geoType.getType().getBinding() == Polygon.class) {
info.setLayerType(LayerType.POLYGON);
} else if (geoType.getType().getBinding() == MultiPolygon.class) {
info.setLayerType(LayerType.MULTIPOLYGON);
}
}
/**
* Adds the edges of a Geometry to the graph.
* May be called multiple times.
* Any dimension of Geometry may be added; the constituent edges are
* extracted.
*
* @param geometry geometry to be added
*/
public void add(Geometry geometry) {
geometry.apply(new GeometryComponentFilter() {
public void filter(Geometry component) {
if (component instanceof LineString) {
add((LineString)component);
}
}
});
}
public void testEverything() throws Exception {
Geometry g1 = reader.read("POLYGON ((40 320, 200 380, 320 80, 40 40, 40 320), (180 280, 80 280, 100 100, 220 140, 180 280))");
Geometry g2 = reader.read("POLYGON ((160 240, 120 240, 120 160, 160 140, 160 240))");
assertEquals(18.97366596, g1.distance(g2), 1E-5);
g2 = reader.read("POLYGON ((160 240, 120 240, 120 160, 180 100, 160 240))");
assertEquals(0.0, g1.distance(g2), 1E-5);
LineString l1 = (LineString) reader.read("LINESTRING(10 10, 20 20, 30 40)");
LineString l2 = (LineString) reader.read("LINESTRING(10 10, 20 20, 30 40)");
assertEquals(0.0, l1.distance(l2), 1E-5);
}
protected static ArrayList<LineString> decompose(GeometryFactory factory, Coordinate[] coordinates, ArrayList<LineString> strings) {
for(Coordinate[] part : decompose(+DATELINE, coordinates)) {
for(Coordinate[] line : decompose(-DATELINE, part)) {
strings.add(factory.createLineString(line));
}
}
return strings;
}
/**
* Create a LineString from a GMLDirectedEdge.
* @param edge
* The edge to convert.
* @return LineString or MultLineString.
*/
public static LineString edgeToLine(GMLDirectedEdge edge) {
Coordinate[] coord = new Coordinate[2];
coord[0] = nodeToCoordinate(edge.getStartNode());
coord[1] = nodeToCoordinate(edge.getEndNode());
return geomFactory.createLineString(coord);
}
boolean isSnapped(List lines, double tol)
{
for (int i = 0; i < lines.size(); i++) {
LineString line = (LineString) lines.get(i);
for (int j = 0; j < line.getNumPoints(); j++) {
Coordinate v = line.getCoordinateN(j);
if (! isSnapped(v, lines)) return false;
}
}
return true;
}
public Geometry getShape(String wtk) throws FactoryException, TransformException {
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), Subject.SRID);
WKTReader reader = new WKTReader(geometryFactory);
MathTransform crsTransform = GeotoolsDataStoreUtils.makeCrsTransform("EPSG:27700");
try {
LineString line = (LineString) reader.read(wtk);
Geometry transformedGeom = JTS.transform(line, crsTransform);
return transformedGeom;
} catch (ParseException e) {
e.printStackTrace();
log.error("Not a valid geometry");
return null;
}
}