com.vividsolutions.jts.geom.Coordinate Java Examples

The following examples show how to use com.vividsolutions.jts.geom.Coordinate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BufferFunctions.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Geometry buildCurveSet(Geometry g, double dist, BufferParameters bufParams)
{
  // --- now construct curve
  OffsetCurveBuilder ocb = new OffsetCurveBuilder(
      g.getFactory().getPrecisionModel(),
      bufParams);
  OffsetCurveSetBuilder ocsb = new OffsetCurveSetBuilder(g, dist, ocb);
  List curves = ocsb.getCurves();
  
  List lines = new ArrayList();
  for (Iterator i = curves.iterator(); i.hasNext(); ) {
  	SegmentString ss = (SegmentString) i.next();
  	Coordinate[] pts = ss.getCoordinates();
  	lines.add(g.getFactory().createLineString(pts));
  }
  Geometry curve = g.getFactory().buildGeometry(lines);
  return curve;
}
 
Example #2
Source File: TiledFeatureService.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Apply clipping to the features in a tile. The tile and its features should already be in map space.
 *
 * @param tile
 *            tile to put features in
 * @param scale
 *            scale
 * @param panOrigin
 *            When panning on the client, only this parameter changes. So we need to be aware of it as we calculate
 *            the maxScreenEnvelope.
 * @throws GeomajasException oops
 */
public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {
	log.debug("clipTile before {}", tile);
	List<InternalFeature> orgFeatures = tile.getFeatures();
	tile.setFeatures(new ArrayList<InternalFeature>());
	Geometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.
	for (InternalFeature feature : orgFeatures) {
		// clip feature if necessary
		if (exceedsScreenDimensions(feature, scale)) {
			log.debug("feature {} exceeds screen dimensions", feature);
			InternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();
			tile.setClipped(true);
			vectorFeature.setClipped(true);
			if (null == maxScreenBbox) {
				maxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));
			}
			Geometry clipped = maxScreenBbox.intersection(feature.getGeometry());
			vectorFeature.setClippedGeometry(clipped);
			tile.addFeature(vectorFeature);
		} else {
			tile.addFeature(feature);
		}
	}
	log.debug("clipTile after {}", tile);
}
 
Example #3
Source File: GamaGeometryType.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static IShape buildHexagon(final double sizeX, final double sizeY, final ILocation location) {
	final double x = location.getX();
	final double y = location.getY();
	final Coordinate[] coords = new Coordinate[7];
	coords[0] = new GamaPoint(x - sizeX / 2.0, y);
	coords[1] = new GamaPoint(x - sizeX / 4, y + sizeY / 2);
	coords[2] = new GamaPoint(x + sizeX / 4, y + sizeY / 2);
	coords[3] = new GamaPoint(x + sizeX / 2, y);
	coords[4] = new GamaPoint(x + sizeX / 4, y - sizeY / 2);
	coords[5] = new GamaPoint(x - sizeX / 4, y - sizeY / 2);
	coords[6] = new GamaPoint(coords[0]);
	final Geometry g = GeometryUtils.GEOMETRY_FACTORY
			.createPolygon(GeometryUtils.GEOMETRY_FACTORY.createLinearRing(coords), null);
	return new GamaShape(g);

}
 
Example #4
Source File: ViewPortComponentImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void calculateSize(PdfContext context) {
	setMapId(getMap().getMapId());
	setRasterResolution(getMap().getRasterResolution());

	// calculate origin (uses margins to position)
	Coordinate mapOrigin = getMap().getLocation();
	Coordinate portOrigin = getLocation();
	if (userX == -1) {
		getConstraint().setMarginX((float) (portOrigin.x - mapOrigin.x) * getMap().getPpUnit());
	} else {
		getConstraint().setMarginX(userX);
	}
	if (userY == -1) {
		getConstraint().setMarginY((float) (portOrigin.y - mapOrigin.y) * getMap().getPpUnit());
	} else {
		getConstraint().setMarginY(userY);
	}

	// calculate ppunit
	setPpUnit(getMap().getPpUnit() * zoomScale);
	super.calculateSize(context);
}
 
Example #5
Source File: BezierSplineFactory.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
public static Coordinate[] createBezierSpline(Coordinate p1, Coordinate p2, Coordinate p3, Coordinate p4, double dist) {
	ArrayList<Coordinate> ret = new ArrayList<Coordinate>();
	double t = 0.0;
	Coordinate prevCoord = p1;
	ret.add(prevCoord);
	do {
		Coordinate coord = cubicBezier(p1, p2, p3, p4, t);
		if (prevCoord.distance(coord) >= dist) {
			ret.add(coord);
			prevCoord = coord;
		}
		t += 0.01;
	}
	while (t < 1.0);
	if (ret.get(ret.size()-1).distance(p4) > dist/4.0) ret.add(p4);
	return ret.toArray(new Coordinate[ret.size()]);
}
 
Example #6
Source File: CreateRandomShapeFunctions.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Geometry randomSegmentsInGrid(Geometry g, int nPts) {
  Envelope env = FunctionsUtil.getEnvelopeOrDefault(g);
  GeometryFactory geomFact = FunctionsUtil.getFactoryOrDefault(g);

  int nCell = (int) Math.sqrt(nPts) + 1;

  double xLen = env.getWidth() / nCell;
  double yLen = env.getHeight() / nCell;

  List lines = new ArrayList();

  for (int i = 0; i < nCell; i++) {
    for (int j = 0; j < nCell; j++) {
      double x0 = env.getMinX() + i * xLen + xLen * Math.random();
      double y0 = env.getMinY() + j * yLen + yLen * Math.random();
      double x1 = env.getMinX() + i * xLen + xLen * Math.random();
      double y1 = env.getMinY() + j * yLen + yLen * Math.random();
      lines.add(geomFact.createLineString(new Coordinate[] {
          new Coordinate(x0, y0), new Coordinate(x1, y1) }));
    }
  }
  return geomFact.buildGeometry(lines);
}
 
Example #7
Source File: Main.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: StringContentTilePainter.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Initialize this painter with all the info it needs.
 * 
 * @param layer
 *            The vector layer wherein the tiles lie.
 * @param style
 *            The rendering style.
 * @param renderer
 *            Rendering output type: "SVG" or "VML".
 * @param scale
 *            The current client-side scale. Needed for creating the world to view space coordinate transformer.
 * @param panOrigin
 *            The current origin may differ, depending on whether or not the client has been panning.Needed for
 *            creating the world to view space coordinate transformer.
 * @param geoService
 *            geo service for geometry conversions
 * @param textService
 *            text service for string sizes
 */
public StringContentTilePainter(VectorLayer layer, NamedStyleInfo style, String renderer, double scale,
		Coordinate panOrigin, GeoService geoService, TextService textService) {
	this.layer = layer;
	// @todo: duplicate code, can we just depend on the VectorLayerService ?
	if (style == null) {
		// no style specified, take the first
		style = layer.getLayerInfo().getNamedStyleInfos().get(0);
	} else if (style.getFeatureStyles().isEmpty()) {
		// only name specified, find it
		style = layer.getLayerInfo().getNamedStyleInfo(style.getName());
	}

	this.style = style;
	this.renderer = renderer;
	this.scale = scale;
	this.panOrigin = panOrigin;
	this.geoService = geoService;
	this.textService = textService;
}
 
Example #9
Source File: AbstractTrajectoryEnvelopeCoordinator.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate obstacles representing the placement(s) of a given robot in given poses.
 * @param robotID The ID of the robot whose footprint should be used.
 * @param obstaclePoses The poses of the footprint.
 * @return A {@link Geometry} that has the shape of the given robot's footprint, placed in each of the the given {@link Pose}s. 
 */
public Geometry[] makeObstacles(int robotID, Pose ... obstaclePoses) {
	ArrayList<Geometry> ret = new ArrayList<Geometry>();
	for (Pose p : obstaclePoses) {
		GeometryFactory gf = new GeometryFactory();
		Coordinate[] footprint = this.getFootprint(robotID);
		Coordinate[] newFoot = new Coordinate[footprint.length+1];
		for (int j = 0; j < footprint.length; j++) {
			newFoot[j] = footprint[j];
		}
		newFoot[footprint.length] = footprint[0];
		Geometry obstacle = gf.createPolygon(newFoot);
		AffineTransformation at = new AffineTransformation();
		at.rotate(p.getTheta());
		at.translate(p.getX(), p.getY());
		obstacle = at.transform(obstacle);
		ret.add(obstacle);
		metaCSPLogger.fine("Made obstacle for Robot" + robotID + " in pose " + p);
	}
	return ret.toArray(new Geometry[ret.size()]);
}
 
Example #10
Source File: AbstractStreamDrawTool.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void mouseLocationChanged(MouseEvent e) {
  try {
    if ((e.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) 
        == InputEvent.BUTTON1_DOWN_MASK) {
      Coordinate newCoord = toModelCoordinate(e.getPoint());
      if (newCoord.distance(lastCoordinate()) < gridSize())
        return;
      //add(toModelSnapped(e.getPoint()));
      add(newCoord);
    }

    tentativeCoordinate = toModelSnapped(e.getPoint());
    redrawIndicator();
  } catch (Throwable t) {
  }
}
 
Example #11
Source File: ValidPanel.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
void btnSimple_actionPerformed(ActionEvent e) 
{
	boolean isSimple = true;
	Coordinate nonSimpleLoc = null;
	if (testCase.getGeometry(0) != null) {
    IsSimpleOp simpleOp = new IsSimpleOp(testCase.getGeometry(0));
    isSimple = simpleOp.isSimple();
    nonSimpleLoc = simpleOp.getNonSimpleLocation(); 
  }
  String msg = isSimple ?
  		""
  		: "Self-intersection at " + WKTWriter.toPoint(nonSimpleLoc);
  taInvalidMsg.setText(msg);
  txtIsValid.setText(isSimple ? "Y" : "N");
  setMarkPoint(nonSimpleLoc);
}
 
Example #12
Source File: MiscellaneousTest.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testCoordinateNaN() {
  Coordinate c1 = new Coordinate();
  assertTrue(! Double.isNaN(c1.x));
  assertTrue(! Double.isNaN(c1.y));
  assertTrue(Double.isNaN(c1.z));

  Coordinate c2 = new Coordinate(3,4);
  assertEquals(3,c2.x,1E-10);
  assertEquals(4,c2.y,1E-10);
  assertTrue(Double.isNaN(c2.z));

  assertEquals(c1,c1);
  assertEquals(c2,c2);
  assertTrue(! c1.equals(c2));
  assertEquals(new Coordinate(),new Coordinate(0,0));
  assertEquals(new Coordinate(3,5),new Coordinate(3,5));
  assertEquals(new Coordinate(3,5,Double.NaN),new Coordinate(3,5,Double.NaN));
  assertTrue(new Coordinate(3,5,0).equals(new Coordinate(3,5,Double.NaN)));
}
 
Example #13
Source File: SplineFactory.java    From coordination_oru with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a Catmull-Rom spline based on the given control points.
 * The generated curve starts in the first control point and ends
 * in the last control point.
 * In addition, the curve intersects all the control points.
 * 
 * @param controlPoints  Control points of spline.
 * @param nParts Number of parts to divide each leg into.
 * @return A Catmull-Rom spline based on the given control points.
 */
public static Spline3D createCatmullRom (Coordinate[] controlPoints, int nParts) {
	double[] cPoints = new double[controlPoints.length*3];
	int counter = 0;
	for (int i = 0; i < controlPoints.length; i++) {
		cPoints[counter] = controlPoints[i].x;
		cPoints[counter+1] = controlPoints[i].y;
		cPoints[counter+2] = controlPoints[i].z;
		counter+=3;
	}
	return new Spline3D(new CatmullRomSpline (cPoints, nParts++).generate(), controlPoints, Spline3D.Type.SPLINE_CATMULL_ROM);
}
 
Example #14
Source File: RobustLineIntersectorTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testCollinear2() {
  RobustLineIntersector i = new RobustLineIntersector();
  Coordinate p1 = new Coordinate(10, 10);
  Coordinate p2 = new Coordinate(20, 10);
  Coordinate q1 = new Coordinate(20, 10);
  Coordinate q2 = new Coordinate(30, 10);
  i.computeIntersection(p1, p2, q1, q2);
  assertEquals(RobustLineIntersector.POINT_INTERSECTION, i.getIntersectionNum());
  assertTrue(!i.isProper());
  assertTrue(i.hasIntersection());
}
 
Example #15
Source File: KdTree.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Converts a collection of {@link KdNode}s 
 * to an array of {@link Coordinate}s,
 * specifying whether repeated nodes should be represented
 * by multiple coordinates.
 * 
 * @param kdnodes a collection of nodes
 * @param includeRepeated true if repeated nodes should 
 *   be included multiple times
 * @return an array of the coordinates represented by the nodes
 */
public static Coordinate[] toCoordinates(Collection kdnodes, boolean includeRepeated) {
  CoordinateList coord = new CoordinateList();
  for (Iterator it = kdnodes.iterator(); it.hasNext();) {
    KdNode node = (KdNode) it.next();
    int count = includeRepeated ? node.getCount() : 1;
    for (int i = 0; i < count; i++) {
     coord.add(node.getCoordinate(), true);
    }
  }
  return coord.toCoordinateArray();
}
 
Example #16
Source File: GeometryCoordinateReplacer.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Gets the snapped coordinate array for an atomic geometry,
 * or null if it has collapsed.
 * 
 * @return the snapped coordinate array for this geometry
 * @return null if the snapped coordinates have collapsed, or are missing
 */
public CoordinateSequence edit(CoordinateSequence coordSeq, Geometry geometry, GeometryFactory targetFactory) {
  if (geometryLinesMap.containsKey(geometry)) {
    Coordinate[] pts = (Coordinate[]) geometryLinesMap.get(geometry);
    // Assert: pts should always have length > 0
    boolean isValidPts = isValidSize(pts, geometry);
    if (! isValidPts) return null;
    return targetFactory.getCoordinateSequenceFactory().create(pts);
  }
  //TODO: should this return null if no matching snapped line is found
  // probably should never reach here?
  return coordSeq;
}
 
Example #17
Source File: DefaultDocumentTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private DefaultConfigurationVisitor getDefaultVisitor(double x, double y, float widthInUnits) {
	// 842, 595
	DefaultConfigurationVisitor config = new DefaultConfigurationVisitor();
	config.setApplicationId("application");
	config.setMapId("mainMap");
	config.setMapRasterResolution(72);
	config.setMapPpUnit(822 / widthInUnits);
	config.setMapLocation(new Coordinate(x, y));
	config.setTitle("Africa");
	return config;
}
 
Example #18
Source File: BrowserVisualization.java    From coordination_oru with GNU General Public License v3.0 5 votes vote down vote up
public void guessInitialTransform(double robotDimension, Pose ... robotPoses) {
	BrowserVisualizationSocket.initialScale = getScreenDPI()/robotDimension;
	double avgX = 0;
	double avgY = 0;
	for (int i = 0; i < robotPoses.length; i++) {
		avgX += robotPoses[i].getX();
		avgY += robotPoses[i].getY();
	}
	avgX /= robotPoses.length;
	avgY /= robotPoses.length;
	avgY -= 0.45*(getScreenHeight()/getScreenDPI());
	BrowserVisualizationSocket.initialTranslation = new Coordinate(avgX,avgY);		
}
 
Example #19
Source File: GeoUtils.java    From gtfs-validator with MIT License 5 votes vote down vote up
/**
 * From
 * http://gis.stackexchange.com/questions/28986/geotoolkit-conversion-from
 * -lat-long-to-utm
 */
public static int getEPSGCodefromUTS(Coordinate refLonLat) {
	// define base EPSG code value of all UTM zones;
	int epsg_code = 32600;
	// add 100 for all zones in southern hemisphere
	if (refLonLat.y < 0) {
		epsg_code += 100;
	}
	// finally, add zone number to code
	epsg_code += getUTMZoneForLongitude(refLonLat.x);

	return epsg_code;
}
 
Example #20
Source File: SegmentPointComparatorTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkNodePosition(int octant,
    double x0, double y0,
  double x1, double y1,
  int expectedPositionValue
  )
{
  int posValue = SegmentPointComparator.compare(octant,
      new Coordinate(x0, y0),
      new Coordinate(x1, y1)
      );
  assertTrue(posValue == expectedPositionValue);
}
 
Example #21
Source File: GeometryUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static void translate(final Geometry geometry, final double dx, final double dy, final double dz) {
	geometry.apply((final Coordinate p) -> {
		p.x += dx;
		p.y += dy;
		p.z += dz;
	});
	geometry.geometryChanged();
}
 
Example #22
Source File: SpatialIndexFunctions.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry kdTreeQuery(Geometry pts, Geometry queryEnv, double tolerance)
{
  KdTree index = buildKdTree(pts, tolerance);
  // if no query env provided query everything inserted 
  if (queryEnv == null) queryEnv = pts;
  List result = index.query(queryEnv.getEnvelopeInternal());
  Coordinate[] resultCoords = KdTree.toCoordinates(result);
  return pts.getFactory().createMultiPoint(resultCoords);
}
 
Example #23
Source File: LengthIndexedLineTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * From GEOS Ticket #323
 */
public void testProjectExtractPoint()
{
  Geometry linearGeom = read("MULTILINESTRING ((0 2, 0 0), (-1 1, 1 1))");
  LengthIndexedLine indexedLine = new LengthIndexedLine(linearGeom);
  double index = indexedLine.project(new Coordinate(1, 0));
  Coordinate pt = indexedLine.extractPoint(index);
  assertTrue(pt.equals(new Coordinate(0, 0)));
}
 
Example #24
Source File: CGAlgorithms.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes the length of a linestring specified by a sequence of points.
 * 
 * @param pts
 *          the points specifying the linestring
 * @return the length of the linestring
 */
public static double length(CoordinateSequence pts)
{
  // optimized for processing CoordinateSequences
  int n = pts.size();
  if (n <= 1)
    return 0.0;

  double len = 0.0;

  Coordinate p = new Coordinate();
  pts.getCoordinate(0, p);
  double x0 = p.x;
  double y0 = p.y;

  for (int i = 1; i < n; i++) {
    pts.getCoordinate(i, p);
    double x1 = p.x;
    double y1 = p.y;
    double dx = x1 - x0;
    double dy = y1 - y0;

    len += Math.sqrt(dx * dx + dy * dy);

    x0 = x1;
    y0 = y1;
  }
  return len;
}
 
Example #25
Source File: ConvexHullTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testAllIdenticalPoints() throws Exception {
  Coordinate[] pts = new Coordinate[100];
  for (int i = 0; i < 100; i++)
    pts[i] = new Coordinate(0,0);
  ConvexHull ch = new ConvexHull(pts, geometryFactory);
  Geometry actualGeometry = ch.getConvexHull();
  Geometry expectedGeometry = reader.read("POINT (0 0)");
  assertTrue(expectedGeometry.equalsExact(actualGeometry));
}
 
Example #26
Source File: CGAlgorithmsTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testDistancePointLinePerpendicular() {
  assertEquals(0.5, CGAlgorithms.distancePointLinePerpendicular(
      new Coordinate(0.5, 0.5), new Coordinate(0,0), new Coordinate(1,0)), 0.000001);
  assertEquals(0.5, CGAlgorithms.distancePointLinePerpendicular(
      new Coordinate(3.5, 0.5), new Coordinate(0,0), new Coordinate(1,0)), 0.000001);
  assertEquals(0.707106, CGAlgorithms.distancePointLinePerpendicular(
      new Coordinate(1,0), new Coordinate(0,0), new Coordinate(1,1)), 0.000001);
}
 
Example #27
Source File: MiscellaneousTest2.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testUniqueCoordinateArrayFilter() throws Exception {
  Geometry g = reader.read(
        "MULTIPOINT(10 10, 20 20, 30 30, 20 20, 10 10)");
  UniqueCoordinateArrayFilter f = new UniqueCoordinateArrayFilter();
  g.apply(f);
  assertEquals(3, f.getCoordinates().length);
  assertEquals(new Coordinate(10, 10), f.getCoordinates()[0]);
  assertEquals(new Coordinate(20, 20), f.getCoordinates()[1]);
  assertEquals(new Coordinate(30, 30), f.getCoordinates()[2]);
}
 
Example #28
Source File: PreparedPolygonIntersectsStressTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void run(int nPts)
  {
//  	Geometry poly = createCircle(new Coordinate(0, 0), 100, nPts);
  	Geometry poly = createSineStar(new Coordinate(0, 0), 100, nPts);
  	System.out.println(poly);
  	
    System.out.println();
    //System.out.println("Running with " + nPts + " points");
    test(poly);
  }
 
Example #29
Source File: NodeMap.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method expects that a node has a coordinate value.
 */
public Node addNode(Coordinate coord)
{
  Node node = (Node) nodeMap.get(coord);
  if (node == null) {
    node = nodeFact.createNode(coord);
    nodeMap.put(coord, node);
  }
  return node;
}
 
Example #30
Source File: BoxBandTool.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected Shape getShape()
{
  if (zoomBoxEnd == null) return null;
  
  Envelope envModel = getEnvelope();
  
  Point2D base = toView(new Coordinate(envModel.getMinX(), envModel.getMaxY()));
  double width = toView(envModel.getWidth());
  double height = toView(envModel.getHeight());
  return new Rectangle2D.Double(base.getX(), base.getY(), width, height);
}