Created
November 10, 2011 23:46
-
-
Save guziy/1356654 to your computer and use it in GitHub Desktop.
Java affine transform using JTS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.vividsolutions.jts.geom.Coordinate; | |
import com.vividsolutions.jts.geom.Geometry; | |
import com.vividsolutions.jts.geom.GeometryFactory; | |
import com.vividsolutions.jts.geom.LinearRing; | |
import com.vividsolutions.jts.geom.util.AffineTransformationBuilder; | |
import com.vividsolutions.jts.geom.util.NoninvertibleTransformationException; | |
import org.geotools.geometry.jts.JTSFactoryFinder; | |
/** | |
* | |
* @author huziy | |
*/ | |
public class TestCreateGeometry { | |
public static void main(String[] args) | |
throws NoninvertibleTransformationException { | |
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); | |
double width = 10.0; | |
Coordinate c1 = new Coordinate(6,7); | |
Coordinate c2 = new Coordinate(10,10); | |
double height = c1.distance(c2); | |
//vector perpendicular to c1c2 | |
Coordinate c = new Coordinate((c1.y - c2.y) / height * width / 2.0 , (c2.x - c1.x) / height * width / 2.0); | |
Coordinate middle = new Coordinate(0.5 * (c1.x + c2.x), 0.5 * (c1.y + c2.y)); | |
Coordinate perpendicular = new Coordinate(middle.x + c.x, middle.y + c.y); | |
Coordinate perpendDest = new Coordinate(0.5, 1.0); //impose it to be like that in the transformed plane | |
//transform the points to the coordinates with the lower left at the corner of the crs | |
//and edges parellel to the axes | |
Coordinate c1Dest = new Coordinate(0, 0.5); | |
Coordinate c2Dest = new Coordinate(1, 0.5); | |
AffineTransformationBuilder builder = new AffineTransformationBuilder(c1, c2, perpendicular, c1Dest, | |
c2Dest, perpendDest); | |
//work from point1 and create linear ring of points | |
Coordinate[] coords = new Coordinate[]{ | |
new Coordinate(0,0), new Coordinate(0,1), new Coordinate(1,1), new Coordinate(1,0), null | |
}; | |
coords[4] = coords[0]; | |
LinearRing ring = geometryFactory.createLinearRing(coords); | |
Geometry rect = geometryFactory.createPolygon(ring, null); | |
rect = builder.getTransformation().getInverse().transform(rect); | |
System.out.println("Perimeters"); | |
System.out.println(rect.getLength()); | |
System.out.println(2 * (height + width)); | |
System.out.println("Areas"); | |
System.out.println(rect.getArea()); | |
System.out.println(width * height); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment