org.geotools.geometry.jts.JTS Java Examples

The following examples show how to use org.geotools.geometry.jts.JTS. 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: WmsLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testNormalEncoded() throws Exception {
	Envelope googleEnvelope = new Envelope(10000, 10010, 5000, 5010);

	// back-transform envelope to latlon
	Crs google = geoService.getCrs2(MERCATOR);
	Crs latlon = geoService.getCrs2(LONLAT);
	Envelope latlonEnvelope = geoService.transform(JTS.toGeometry(googleEnvelope), google, latlon)
			.getEnvelopeInternal();

	// back-transform scale to latlon
	double latlonScale = ZOOMED_IN_SCALE * googleEnvelope.getWidth() / latlonEnvelope.getWidth();

	// paint with re-projection (affine is fine for now...:-)
	List<RasterTile> tiles = escapeBlue.paint(latlon, latlonEnvelope, latlonScale);
	Assert.assertEquals(1, tiles.size());
	RasterTile tile = tiles.get(0);

	// ZOOMED_IN_SCALE 1E-4 corresponds to level 4 with current algorithm !!!!
	assertThat(tile.getUrl()).isEqualTo("http://apps.geomajas.org/geoserver/wms?SERVICE=WMS&" +
			"layers=geomajas%3Abluemarble&WIDTH=512&HEIGHT=512&bbox=0,0,45,45&format=image/png&version=1.1.1&" +
			"srs=EPSG%3A4326&styles=&what%3F=value%2Bmore%21&request=GetMap");

}
 
Example #2
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static SimpleFeature crsTransform(
    final SimpleFeature entry,
    final SimpleFeatureType reprojectedType,
    final MathTransform transform) {
  SimpleFeature crsEntry = entry;

  if (transform != null) {
    // we can use the transform we have already calculated for this
    // feature
    try {

      // this will clone the feature and retype it to Index CRS
      crsEntry = SimpleFeatureBuilder.retype(entry, reprojectedType);

      // this will transform the geometry
      crsEntry.setDefaultGeometry(
          JTS.transform((Geometry) entry.getDefaultGeometry(), transform));
    } catch (MismatchedDimensionException | TransformException e) {
      LOGGER.warn(
          "Unable to perform transform to specified CRS of the index, the feature geometry will remain in its original CRS",
          e);
    }
  }

  return crsEntry;
}
 
Example #3
Source File: CoordinateCircleDistanceFn.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public double measure(final Coordinate c1, final Coordinate c2) {
  try {
    return JTS.orthodromicDistance(c1, c2, getCRS());
  } catch (final TransformException e) {
    throw new RuntimeException("Failed to transform coordinates to provided CRS", e);
  } catch (final java.lang.AssertionError ae) {
    // weird error with orthodromic distance..when distance is too close
    // (0.05 meter), it fails the tolerance test
    LOGGER.info("when distance is too close(0.05 meter), it fails the tolerance test", ae);

    final GeodeticCalculator calc = new GeodeticCalculator(getCRS());
    calc.setStartingGeographicPoint(c1.x, c1.y);
    calc.setDestinationGeographicPoint(c2.x, c2.y);
    return ((DefaultEllipsoid) calc.getEllipsoid()).orthodromicDistance(
        calc.getStartingGeographicPoint().getX(),
        calc.getStartingGeographicPoint().getY(),
        calc.getDestinationGeographicPoint().getX(),
        calc.getDestinationGeographicPoint().getY());
  }
}
 
Example #4
Source File: ExtractGeometryFilterVisitorTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testDWithinDateLine() throws CQLException, TransformException, ParseException {

  final Filter filter =
      CQL.toFilter(
          String.format(
              "DWITHIN(%s, POINT(179.9998 0.79), 13.7, kilometers)",
              geomAttributeName));
  final Query query = new Query("type", filter);

  final ExtractGeometryFilterVisitorResult result =
      (ExtractGeometryFilterVisitorResult) query.getFilter().accept(visitorWithDescriptor, null);
  final Geometry geometry = result.getGeometry();
  assertNotNull(geometry);
  for (final Coordinate coord : geometry.getCoordinates()) {

    assertEquals(
        13707.1,
        JTS.orthodromicDistance(
            coord,
            new Coordinate(179.9999, 0.79),
            GeometryUtils.getDefaultCRS()),
        2000);
  }
}
 
Example #5
Source File: ExtractGeometryFilterVisitorTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testDWithin() throws CQLException, TransformException, ParseException {

  final Filter filter =
      CQL.toFilter(
          String.format(
              "DWITHIN(%s, POINT(-122.7668 0.4979), 233.7, meters)",
              geomAttributeName));
  final Query query = new Query("type", filter);

  final ExtractGeometryFilterVisitorResult result =
      (ExtractGeometryFilterVisitorResult) query.getFilter().accept(visitorWithDescriptor, null);
  final Geometry geometry = result.getGeometry();
  assertNotNull(geometry);
  for (final Coordinate coord : geometry.getCoordinates()) {

    assertEquals(
        233.7,
        JTS.orthodromicDistance(
            coord,
            new Coordinate(-122.7668, 0.4979),
            GeometryUtils.getDefaultCRS()),
        2);
  }
}
 
Example #6
Source File: OsmLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testReprojectOne() throws Exception {
	Envelope googleEnvelope = new Envelope(10000, 10010, 5000, 5010);
	// back-transform envelope to latlon
	Crs google = geoService.getCrs2("EPSG:900913");
	Crs latlon = geoService.getCrs2("EPSG:4326");
	Envelope latlonEnvelope = geoService.transform(JTS.toGeometry(googleEnvelope), google, latlon)
			.getEnvelopeInternal();
	// back-transform scale to latlon
	double latlonScale = ZOOMED_IN_SCALE * googleEnvelope.getWidth() / latlonEnvelope.getWidth();
	// paint with reprojection (affine is fine for now...:-)
	List<RasterTile> tiles = osm.paint(latlon, latlonEnvelope, latlonScale);
	Assert.assertEquals(1, tiles.size());
	RasterTile tile = tiles.get(0);
	Assert.assertEquals("http://a.tile.openstreetmap.org/4/8/7.png", tile.getUrl());
	Assert.assertEquals(4, tile.getCode().getTileLevel());
	Assert.assertEquals(8, tile.getCode().getX());
	Assert.assertEquals(7, tile.getCode().getY());
	Assert.assertEquals(0.0, tile.getBounds().getX(), DELTA);
	Assert.assertEquals(-244.0, tile.getBounds().getY(), DELTA);
	Assert.assertEquals(244.0, tile.getBounds().getHeight(), DELTA);
	Assert.assertEquals(250.0, tile.getBounds().getWidth(), DELTA);
}
 
Example #7
Source File: GeoUtils.java    From gtfs-validator with MIT License 6 votes vote down vote up
private static ProjectedCoordinate convertLonLatToEuclidean(
		Coordinate lonlat) {

	final MathTransform transform = getTransform(lonlat);
	final Coordinate to = new Coordinate();

	// the transform seems to swap the lat lon pairs
	Coordinate latlon = new Coordinate(lonlat.y, lonlat.x);

	try {
		JTS.transform(latlon, to, transform);
	} catch (final TransformException e) {
		e.printStackTrace();
	}

	return new ProjectedCoordinate(transform, new Coordinate(to.y, to.x), lonlat);
}
 
Example #8
Source File: RasterizedSpatialiteLasLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private static void drawLevels( ASpatialDb db, ColorInterpolator colorInterp, PointTransformation pointTransformation,
        Geometry polygon, Graphics2D gr, int lasLevelsNum, MathTransform data2NwwTransform, boolean doIntensity,
        int finalTileSize ) throws Exception {
    int maxPerImage = 100000;
    List<LasLevel> lasLevels = LasLevelsTable.getLasLevels(db, lasLevelsNum, polygon);

    int size = lasLevels.size();
    if (size > 0) {
        int jump = size / maxPerImage;
        for( int i = 0; i < size; i = i + 1 + jump ) {
            LasLevel lasLevel = lasLevels.get(i);
            Polygon levelPolygon = lasLevel.polygon;
            Geometry polygonNww = JTS.transform(levelPolygon, data2NwwTransform);
            GeneralPath p = polygonToPath(pointTransformation, polygonNww, finalTileSize);
            Color c = colorInterp.getColorFor(doIntensity ? lasLevel.avgIntensity : lasLevel.avgElev);
            gr.setPaint(c);
            gr.fill(p);
        }
    }
}
 
Example #9
Source File: RasterizedSpatialiteLasLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private static void drawCells( ASpatialDb db, ColorInterpolator colorInterp, PointTransformation pointTransformation,
        Geometry polygon, Graphics2D gr, MathTransform data2NwwTransform, boolean doIntensity, int finalTileSize )
        throws Exception {
    int maxPerImage = 100000;
    List<LasCell> lasCells = LasCellsTable.getLasCells(db, null, polygon, true, true, false, false, false, maxPerImage);
    int size = lasCells.size();
    if (size > 0) {
        int jump = size / maxPerImage;
        for( int i = 0; i < size; i = i + 1 + jump ) {
            LasCell lasCell = lasCells.get(i);
            if (lasCell.pointsCount == 0) {
                continue;
            }
            Polygon levelPolygon = lasCell.polygon;
            Geometry polygonNww = JTS.transform(levelPolygon, data2NwwTransform);
            GeneralPath p = polygonToPath(pointTransformation, polygonNww, finalTileSize);
            Color c = colorInterp.getColorFor(doIntensity ? lasCell.avgIntensity : lasCell.avgElev);
            gr.setPaint(c);
            gr.fill(p);
        }
    }
}
 
Example #10
Source File: RL2NwwLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public RL2NwwLayer( Rasterlite2Coverage rasterCoverage, Integer tileSize ) throws Exception {
    super(makeLevels(rasterCoverage, tileSize));
    this.layerName = rasterCoverage.getName();

    Envelope bounds = rasterCoverage.getBounds();
    double w = bounds.getMinX();
    double s = bounds.getMinY();
    double e = bounds.getMaxX();
    double n = bounds.getMaxY();

    double centerX = w + (e - w) / 2.0;
    double centerY = s + (n - s) / 2.0;
    Coordinate centerCoordinate = new Coordinate(centerX, centerY);

    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
    CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromSrid(rasterCoverage.getSrid());

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
    centerCoordinateLL = JTS.transform(centerCoordinate, null, transform);

    this.setUseTransparentTextures(true);

}
 
Example #11
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 #12
Source File: SwtMapPane.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public void setCrs(final CoordinateReferenceSystem crs) {
	try {
		final ReferencedEnvelope rEnv = getDisplayArea();

		final CoordinateReferenceSystem sourceCRS = rEnv.getCoordinateReferenceSystem();
		final CoordinateReferenceSystem targetCRS = crs;

		final MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
		final com.vividsolutions.jts.geom.Envelope newJtsEnv = JTS.transform(rEnv, transform);

		final ReferencedEnvelope newEnvelope = new ReferencedEnvelope(newJtsEnv, targetCRS);
		content.getViewport().setBounds(newEnvelope);
		fullExtent = null;
		doSetDisplayArea(newEnvelope);

	} catch (final Exception e) {
		e.printStackTrace();
	}
}
 
Example #13
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION")
public Geometry transform(Geometry source, CrsTransform crsTransform) {
	try {
		if (crsTransform.isTransforming()) {
			Geometry transformableArea = crsTransform.getTransformableGeometry();
			if (null != transformableArea && !transformableArea.covers(source)) {
				source = source.intersection(transformableArea);
			}
			return JTS.transform(source, crsTransform);
		} else {
			return source;
		}
	} catch (Exception e) { // NOSONAR typically TopologyException, TransformException or FactoryException
		logEnvelopeSuggestCrsTransformInfo(crsTransform.getId(), source, e);
		return createEmptyGeometryForClass(source.getClass());
	}
}
 
Example #14
Source File: MBTilesHelper.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read the image of a tile from a generic geotools coverage reader.
 * 
 * @param reader the reader, expected to be in CRS 3857.
 * @param x the tile x.
 * @param y the tile y.
 * @param zoom the zoomlevel.
 * @return the image.
 * @throws IOException 
 */
public static BufferedImage readGridcoverageImageForTile( AbstractGridCoverage2DReader reader, int x, int y, int zoom,
        CoordinateReferenceSystem resampleCrs ) throws IOException {
    double north = tile2lat(y, zoom);
    double south = tile2lat(y + 1, zoom);
    double west = tile2lon(x, zoom);
    double east = tile2lon(x + 1, zoom);

    Coordinate ll = new Coordinate(west, south);
    Coordinate ur = new Coordinate(east, north);

    try {
        CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;

        MathTransform transform = CRS.findMathTransform(sourceCRS, resampleCrs);
        ll = JTS.transform(ll, null, transform);
        ur = JTS.transform(ur, null, transform);
    } catch (Exception e) {
        e.printStackTrace();
    }

    BufferedImage image = ImageUtilities.imageFromReader(reader, TILESIZE, TILESIZE, ll.x, ur.x, ll.y, ur.y, resampleCrs);
    return image;
}
 
Example #15
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Coordinate transform(Coordinate source, CrsTransform crsTransform) {
	try {
		if (crsTransform.isTransforming()) {
			Envelope transformableArea = crsTransform.getTransformableEnvelope();
			if (null == transformableArea || transformableArea.contains(source)) {
				return JTS.transform(source, new Coordinate(), crsTransform);
			}
			return null;
		} else {
			return source;
		}
	} catch (Exception e) { // NOSONAR typically TopologyException, TransformException or FactoryException
		logEnvelopeSuggestCrsTransformInfo(crsTransform.getId(), source, e);
		return null;
	}
}
 
Example #16
Source File: GeoUtils.java    From collect-earth with MIT License 5 votes vote down vote up
public static Point transformToWGS84(double longitude, double latitude, String sourceEpsgCode ) throws TransformException, FactoryException {
	final GeometryFactory gf = new GeometryFactory();
	final Coordinate c = new Coordinate(longitude, latitude);
	Point p = gf.createPoint(c);
	final CoordinateReferenceSystem sourceEpsgCRS = CRS.decode(sourceEpsgCode);
	final MathTransform mathTransform = CRS.findMathTransform(sourceEpsgCRS, DefaultGeographicCRS.WGS84, false);
	return (Point) JTS.transform(p, mathTransform);		
}
 
Example #17
Source File: ExtractGeometryFilterVisitor.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public Object visit(final BBOX filter, final Object data) {
  if (attributeOfInterest.equals(filter.getExpression1().toString())) {
    final Geometry bbox = bbox(data);
    final BoundingBox referencedBBox = filter.getBounds();
    Geometry bounds =
        new GeometryFactory().toGeometry(
            new Envelope(
                referencedBBox.getMinX(),
                referencedBBox.getMaxX(),
                referencedBBox.getMinY(),
                referencedBBox.getMaxY()));

    if ((crs != null)
        && (referencedBBox.getCoordinateReferenceSystem() != null)
        && !crs.equals(referencedBBox.getCoordinateReferenceSystem())) {
      try {
        bounds =
            JTS.transform(
                bounds,
                CRS.findMathTransform(referencedBBox.getCoordinateReferenceSystem(), crs, true));
      } catch (MismatchedDimensionException | TransformException | FactoryException e) {
        LOGGER.error("Unable to transforma bbox", e);
      }
    }
    if (bbox != null) {
      return bbox.union(bounds);
    } else {
      return new ExtractGeometryFilterVisitorResult(bounds, CompareOperation.INTERSECTS);
    }
  } else {
    return new ExtractGeometryFilterVisitorResult(infinity(), null);
  }
}
 
Example #18
Source File: TiledRasterLayerService.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getBestZoomLevelForScaleInPixPerMeter(TiledRasterLayerServiceState tileServiceState,
		CrsTransform layerToGoogle, Coordinate mapPosition,
		double scale) {
	double scaleRatio = MAP_UNIT_PER_GOOGLE_METER_DEFAULT;
	try {
		Coordinate mercatorCenter = JTS.transform(mapPosition, new Coordinate(), layerToGoogle);
		Coordinate dx = JTS.transform(new Coordinate(mapPosition.x + 1, mapPosition.y), new Coordinate(),
				layerToGoogle);
		scaleRatio = 1.0 / (dx.x - mercatorCenter.x);
	} catch (TransformException e) {
		log.warn("calculateMapUnitPerGoogleMeter() : transformation failed", e);
	}
	double scaleInPixPerMeter = scale * scaleRatio;
	double screenResolution = 1.0 / scaleInPixPerMeter;
	double[] resolutions = tileServiceState.getResolutions();
	if (screenResolution >= resolutions[0]) {
		return 0;
	} else if (screenResolution <= resolutions[tileServiceState.getMaxZoomLevel()]) {
		return tileServiceState.getMaxZoomLevel();
	} else {
		for (int i = 0; i < tileServiceState.getMaxZoomLevel(); i++) {
			double upper = resolutions[i];
			double lower = resolutions[i + 1];
			if (screenResolution <= upper && screenResolution >= lower) {
				if ((upper - screenResolution) > 2 * (screenResolution - lower)) {
					return i + 1;
				} else {
					return i;
				}
			}
		}
	}
	// should not occur !!!!
	return MAX_ZOOM_LEVEL;
}
 
Example #19
Source File: VectorCrsConversionTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void verify(Coordinate mercator, Coordinate lonlat, double x, double y, double lon, double lat)
		throws Exception {
	Coordinate projected = new Coordinate();
	projected = JTS.transform(mercator, projected, layerToMap);
	Assert.assertEquals(x, mercator.x, TOLERANCE);
	Assert.assertEquals(lon, projected.x, TOLERANCE);
	Assert.assertEquals(lon, lonlat.x, TOLERANCE);
	Assert.assertEquals(y, mercator.y, TOLERANCE);
	Assert.assertEquals(lat, projected.y, TOLERANCE);
	Assert.assertEquals(lat, lonlat.y, TOLERANCE);
}
 
Example #20
Source File: GeoServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testCalcDefaultLabelPosition() throws Exception {
	Geometry geometry;
	GeometryFactory factory = new GeometryFactory(new PrecisionModel(), 4326);
	Coordinate coordinate;
	InternalFeature feature = new InternalFeatureImpl();
	feature.setId("x");
	feature.setLabel("Label x");
	coordinate = geoService.calcDefaultLabelPosition(feature);
	Assert.assertNull(coordinate);

	feature.setGeometry(factory.createMultiPolygon(new Polygon[] {}));
	coordinate = geoService.calcDefaultLabelPosition(feature);
	Assert.assertNull(coordinate);

	feature.setGeometry(JTS.toGeometry(new Envelope(10, 20, 30, 40)));
	coordinate = geoService.calcDefaultLabelPosition(feature);
	// this tests current behaviour, without claims that this is the "best" (or even "good") position
	Assert.assertEquals(15.0, coordinate.x, DELTA);
	Assert.assertEquals(35.0, coordinate.y, DELTA);

	geometry = factory.createLineString(new Coordinate[] { new Coordinate(5,4), new Coordinate(30,10) });
	feature.setGeometry(geometry);
	coordinate = geoService.calcDefaultLabelPosition(feature);
	// this tests current behaviour, without claims that this is the "best" (or even "good") position
	Assert.assertEquals(5.0, coordinate.x, DELTA);
	Assert.assertEquals(4.0, coordinate.y, DELTA);
}
 
Example #21
Source File: TiledRasterLayerService.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private Coordinate getTileIndicesFromMap(CrsTransform mapToLayer, Coordinate centerMapCoor, int zoomLevel)
		throws TransformException {
	Coordinate centerLayerCoor = JTS.transform(centerMapCoor, new Coordinate(), mapToLayer);
	double xIndex = (centerLayerCoor.x + HALF_EQUATOR_IN_METERS) * POWERS_OF_TWO[zoomLevel] / EQUATOR_IN_METERS;
	double yIndex = (-centerLayerCoor.y + HALF_EQUATOR_IN_METERS) * POWERS_OF_TWO[zoomLevel] / EQUATOR_IN_METERS;
	return new Coordinate(xIndex, yIndex);
}
 
Example #22
Source File: OsmLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testReprojectSeveral() throws Exception {
	// move up north to test latlon flattening
	Envelope googleEnvelope = new Envelope(10000, 13000, 6005000, 6008000);
	// back-transform envelope to latlon
	Crs google = geoService.getCrs2("EPSG:900913");
	Crs latlon = geoService.getCrs2("EPSG:4326");
	Envelope latlonEnvelope = geoService.transform(JTS.toGeometry(googleEnvelope), google, latlon)
			.getEnvelopeInternal();
	// back-transform scale to latlon
	double latlonScale = MAX_LEVEL_SCALE * googleEnvelope.getWidth() / latlonEnvelope.getWidth();
	// paint with reprojection (affine is fine for now...:-)
	List<RasterTile> tiles = osm.paint(latlon, latlonEnvelope, latlonScale);
	Assert.assertEquals(4, tiles.size());
	Assert.assertEquals("http://a.tile.openstreetmap.org/14/8196/5735.png", tiles.get(0).getUrl());
	Assert.assertEquals("http://a.tile.openstreetmap.org/14/8196/5736.png", tiles.get(1).getUrl());
	Assert.assertEquals("http://a.tile.openstreetmap.org/14/8197/5735.png", tiles.get(2).getUrl());
	Assert.assertEquals("http://a.tile.openstreetmap.org/14/8197/5736.png", tiles.get(3).getUrl());
	// test first tile
	double width = tiles.get(0).getBounds().getWidth();
	double height = tiles.get(0).getBounds().getHeight();
	double x = tiles.get(0).getBounds().getX();
	double y = tiles.get(0).getBounds().getY();
	Assert.assertEquals(245, width, DELTA);
	Assert.assertEquals(166, height, DELTA);
	Assert.assertEquals(978, x, DELTA);
	Assert.assertEquals(-527802, y, DELTA);
	// test alignment on grid
	for (int i = 0; i <= 1; i++) {
		for (int j = 0; j <= 1; j++) {
			Assert.assertEquals(x + i * width, tiles.get(2 * i + j).getBounds().getX(), DELTA);
			Assert.assertEquals(y + j * height, tiles.get(2 * i + j).getBounds().getY(), DELTA);
			Assert.assertEquals(width, tiles.get(2 * i + j).getBounds().getWidth(), DELTA);
			Assert.assertEquals(height, tiles.get(2 * i + j).getBounds().getHeight(), DELTA);
		}
	}
}
 
Example #23
Source File: WmsLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testNormalOne() throws Exception {
	Envelope googleEnvelope = new Envelope(10000, 10010, 5000, 5010);

	// back-transform envelope to latlon
	Crs google = geoService.getCrs2(MERCATOR);
	Crs latlon = geoService.getCrs2(LONLAT);
	Envelope latlonEnvelope = geoService.transform(JTS.toGeometry(googleEnvelope), google, latlon)
			.getEnvelopeInternal();

	// back-transform scale to latlon
	double latlonScale = ZOOMED_IN_SCALE * googleEnvelope.getWidth() / latlonEnvelope.getWidth();

	// paint with re-projection (affine is fine for now...:-)
	List<RasterTile> tiles = wms.paint(latlon, latlonEnvelope, latlonScale);
	Assert.assertEquals(1, tiles.size());
	RasterTile tile = tiles.get(0);

	// ZOOMED_IN_SCALE 1E-4 corresponds to level 4 with current algorithm !!!!
	Assert.assertEquals("http://apps.geomajas.org/geoserver/wms?SERVICE=WMS&layers=bluemarble&"
			+ "WIDTH=512&HEIGHT=512&bbox=-20,-28,12,4&format=image/jpeg&version=1.1.1&srs=EPSG%3A4326&"
			+ "styles=&request=GetMap", tile.getUrl());

	// Assert.assertEquals("http://apps.geomajas.org/geoserver/wms?SERVICE=WMS&"
	// + "layers=bluemarble&WIDTH=512&HEIGHT=512&"
	// + "bbox=-20.032430835865227,-28.207099921352835,11.947593278789554,3.7729241933019466&"
	// + "format=image/jpeg&version=1.1.1&srs=EPSG%3A4326&styles=&request=GetMap", tile.getUrl());
	Assert.assertEquals(4, tile.getCode().getTileLevel());
	Assert.assertEquals(5, tile.getCode().getX());
	Assert.assertEquals(12, tile.getCode().getY());
	Assert.assertEquals(-223.0, tile.getBounds().getX(), DELTA);
	// Assert.assertEquals(-42.0, tile.getBounds().getY(), DELTA);
	Assert.assertEquals(-45.0, tile.getBounds().getY(), DELTA);
	// Assert.assertEquals(356.0, tile.getBounds().getHeight(), DELTA);
	Assert.assertEquals(357.0, tile.getBounds().getHeight(), DELTA);
	// Assert.assertEquals(356.0, tile.getBounds().getWidth(), DELTA);
	Assert.assertEquals(357.0, tile.getBounds().getWidth(), DELTA);
}
 
Example #24
Source File: CrsTransformImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param id id
 * @param source source CRS
 * @param target target CRS
 * @param mathTransform transformation
 * @param transformableEnvelope bounding bow of transformable area
 */
public CrsTransformImpl(String id, Crs source, Crs target, MathTransform mathTransform,
		Envelope transformableEnvelope) {
	this(id, source, target, mathTransform);
	if (null != transformableEnvelope) {
		this.transformableEnvelope = transformableEnvelope;
		this.transformableBbox = new Bbox(transformableEnvelope.getMinX(), transformableEnvelope.getMinY(),
				transformableEnvelope.getMaxX(), transformableEnvelope.getMaxY());
		this.transformableGeometry = JTS.toGeometry(transformableEnvelope);
	}
}
 
Example #25
Source File: CrsTransformImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param id id
 * @param source source CRS
 * @param target target CRS
 * @param mathTransform transformation
 * @param transformableBbox bounding bow of transformable area
 */
public CrsTransformImpl(String id, Crs source, Crs target, MathTransform mathTransform,
		Bbox transformableBbox) {
	this(id, source, target, mathTransform);
	if (null != transformableBbox) {
		this.transformableBbox = transformableBbox;
		this.transformableEnvelope =
				new Envelope(transformableBbox.getX(), transformableBbox.getMaxX(), transformableBbox.getY(),
						transformableBbox.getMaxY());
		this.transformableGeometry = JTS.toGeometry(transformableEnvelope);
	}
}
 
Example #26
Source File: RDDUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static InsertionIds trimIndexIds(
    final InsertionIds rawIds,
    final Geometry geom,
    final NumericIndexStrategy index) {
  for (final SinglePartitionInsertionIds insertionId : rawIds.getPartitionKeys()) {
    final byte[] partitionKey = insertionId.getPartitionKey();
    final int size = insertionId.getSortKeys().size();
    if (size > 3) {
      final Iterator<byte[]> it = insertionId.getSortKeys().iterator();
      while (it.hasNext()) {
        final byte[] sortKey = it.next();
        final MultiDimensionalNumericData keyTile = index.getRangeForId(partitionKey, sortKey);
        final Envelope other = new Envelope();
        other.init(
            keyTile.getMinValuesPerDimension()[0],
            keyTile.getMaxValuesPerDimension()[0],
            keyTile.getMinValuesPerDimension()[1],
            keyTile.getMaxValuesPerDimension()[1]);
        final Polygon rect = JTS.toGeometry(other);
        if (!RectangleIntersects.intersects(rect, geom)) {
          it.remove();
        }
      }
    }
  }
  return rawIds;
}
 
Example #27
Source File: WmsLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testProxyOne() throws Exception {
	Envelope googleEnvelope = new Envelope(10000, 10010, 5000, 5010);

	// back-transform envelope to latlon
	Crs google = geoService.getCrs2(MERCATOR);
	Crs latlon = geoService.getCrs2(LONLAT);
	Envelope latlonEnvelope = geoService.transform(JTS.toGeometry(googleEnvelope), google, latlon)
			.getEnvelopeInternal();

	// back-transform scale to latlon
	double latlonScale = ZOOMED_IN_SCALE * googleEnvelope.getWidth() / latlonEnvelope.getWidth();

	// paint with re-projection (affine is fine for now...:-)
	List<RasterTile> tiles = proxyWms.paint(latlon, latlonEnvelope, latlonScale);
	Assert.assertEquals(1, tiles.size());
	RasterTile tile = tiles.get(0);

	Assert.assertEquals("./d/wms/proxyBlue/?SERVICE=WMS&layers=bluemarble&WIDTH=512&HEIGHT=512&bbox"
			+ "=-20,-28,12,4&format=image/jpeg&version=1.3.0&crs=EPSG%3A4326&styles=&request=GetMap", tile.getUrl());
	Assert.assertEquals(4, tile.getCode().getTileLevel());
	Assert.assertEquals(5, tile.getCode().getX());
	Assert.assertEquals(12, tile.getCode().getY());
	Assert.assertEquals(-223.0, tile.getBounds().getX(), DELTA);
	Assert.assertEquals(-45.0, tile.getBounds().getY(), DELTA);
	Assert.assertEquals(357.0, tile.getBounds().getHeight(), DELTA);
	Assert.assertEquals(357.0, tile.getBounds().getWidth(), DELTA);

	// Assert.assertEquals("./d/wms/proxyBlue/?SERVICE=WMS&layers=bluemarble&WIDTH=512&HEIGHT=512&"
	// + "bbox=-20.032430835865227,-28.207099921352835,11.947593278789554,3.7729241933019466&"
	// + "format=image/jpeg&version=1.3.0&crs=EPSG%3A4326&styles=&request=GetMap", tile.getUrl());
	// Assert.assertEquals(4, tile.getCode().getTileLevel());
	// Assert.assertEquals(5, tile.getCode().getX());
	// Assert.assertEquals(12, tile.getCode().getY());
	// Assert.assertEquals(-223.0, tile.getBounds().getX(), DELTA);
	// Assert.assertEquals(-42.0, tile.getBounds().getY(), DELTA);
	// Assert.assertEquals(356.0, tile.getBounds().getHeight(), DELTA);
	// Assert.assertEquals(356.0, tile.getBounds().getWidth(), DELTA);
}
 
Example #28
Source File: RestControllerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testEpsg() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setRequestURI("/rest/beans");
	request.setMethod("GET");
	MockHttpServletResponse response = new MockHttpServletResponse();
	// check attribute equality
	request.setParameter("queryable", "stringAttr");
	request.setParameter("stringAttr_eq", "bean1");
	request.setParameter("epsg", "900913");
	ModelAndView mav = adapter.handle(request, response, restController);
	view.render(mav.getModel(), request, response);
	response.flushBuffer();
	Object json = new JSONParser().parse(response.getContentAsString());
	Assert.assertTrue(json instanceof JSONObject);
	JSONObject jsonObject = (JSONObject) json;
	JSONArray features = (JSONArray) jsonObject.get("features");
	JSONObject feature = (JSONObject) features.get(0);
	JSONObject geometry = (JSONObject) feature.get("geometry");
	GeometryJSON g = new GeometryJSON(0);
	Geometry m = g.read(geometry.toJSONString());
	Envelope envelope = new Envelope(0, 1, 0, 1);
	Geometry orig = JTS.toGeometry(envelope);
	Geometry m2 = geoservice.transform(orig, "EPSG:4326", "EPSG:900913");
	// equality check on buffer, JTS equals does not do the trick !
	Assert.assertTrue(m.buffer(0.01).contains(m2));
	Assert.assertTrue(m2.buffer(0.01).contains(m));
}
 
Example #29
Source File: GoogleLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getBestZoomLevelForScaleInPixPerMeter(CrsTransform layerToGoogle, Coordinate mapPosition, 
		double scale) {
	double scaleRatio = MAP_UNIT_PER_GOOGLE_METER_DEFAULT;
	try {
		Coordinate mercatorCenter = JTS.transform(mapPosition, new Coordinate(), layerToGoogle);
		Coordinate dx = JTS.transform(new Coordinate(mapPosition.x + 1, mapPosition.y), new Coordinate(),
				layerToGoogle);
		scaleRatio = 1.0 / (dx.x - mercatorCenter.x);
	} catch (TransformException e) {
		log.warn("calculateMapUnitPerGoogleMeter() : transformation failed", e);
	}
	double scaleInPixPerMeter = scale * scaleRatio;
	double screenResolution = 1.0 / scaleInPixPerMeter;
	if (screenResolution >= resolutions[0]) {
		return 0;
	} else if (screenResolution <= resolutions[maxZoomlevel]) {
		return maxZoomlevel;
	} else {
		for (int i = 0; i < maxZoomlevel; i++) {
			double upper = resolutions[i];
			double lower = resolutions[i + 1];
			if (screenResolution <= upper && screenResolution >= lower) {
				if ((upper - screenResolution) > 2 * (screenResolution - lower)) {
					return i + 1;
				} else {
					return i;
				}
			}
		}
	}
	// should not occur !!!!
	return maxZoomlevel;
}
 
Example #30
Source File: GrassLegacyUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static Envelope reprojectEnvelopeByEpsg( int srcEpsg, int destEpsg, Envelope srcEnvelope )
        throws FactoryException, TransformException {

    CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromSrid(srcEpsg);
    CoordinateReferenceSystem targetCRS = CrsUtilities.getCrsFromSrid(destEpsg);
    MathTransform tr = CRS.findMathTransform(sourceCRS, targetCRS);

    // From that point, I'm not sure which kind of object is returned by
    // getLatLonBoundingBox(). But there is some convenience methods if CRS
    // like:

    return JTS.transform(srcEnvelope, tr);

}