Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class SphericalMercatorUtils {

public static final double MERCATOR_BOUNDS = 20037508.34;
private static final double MERCATOR_FACTOR = MERCATOR_BOUNDS / 180.0;
// latitude lower limit. Below this limit the transformation might result in -Infinity
private static final double LAT_LOWER_LIMIT = Math.nextUp(-90.0);

/**
* Transforms WGS84 longitude to a Spherical mercator longitude
Expand All @@ -29,7 +31,7 @@ public static double lonToSphericalMercator(double lon) {
* Transforms WGS84 latitude to a Spherical mercator latitude
*/
public static double latToSphericalMercator(double lat) {
double y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
double y = Math.log(Math.tan((90 + Math.max(lat, LAT_LOWER_LIMIT)) * Math.PI / 360)) / (Math.PI / 180);
return y * MERCATOR_FACTOR;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,28 @@ public void testLat() {
assertThat(latToSphericalMercator(GeoTileUtils.LATITUDE_MASK), Matchers.closeTo(MERCATOR_BOUNDS, 1e-7));
assertThat(latToSphericalMercator(-GeoTileUtils.LATITUDE_MASK), Matchers.closeTo(-MERCATOR_BOUNDS, 1e-7));
assertThat(latToSphericalMercator(0.0), Matchers.closeTo(0, 1e-7));
final double lat = latToSphericalMercator(
randomValueOtherThanMany(l -> l >= GeoTileUtils.LATITUDE_MASK || l <= -GeoTileUtils.LATITUDE_MASK, GeometryTestUtils::randomLat)
);
assertThat(lat, Matchers.greaterThanOrEqualTo(-MERCATOR_BOUNDS));
assertThat(lat, Matchers.lessThanOrEqualTo(MERCATOR_BOUNDS));
{
final double lat = latToSphericalMercator(
randomValueOtherThanMany(
l -> l >= GeoTileUtils.LATITUDE_MASK || l <= -GeoTileUtils.LATITUDE_MASK,
GeometryTestUtils::randomLat
)
);
assertThat(lat, Matchers.greaterThanOrEqualTo(-MERCATOR_BOUNDS));
assertThat(lat, Matchers.lessThanOrEqualTo(MERCATOR_BOUNDS));
}
{
// out of bounds values
final double lat = latToSphericalMercator(randomDoubleBetween(GeoTileUtils.LATITUDE_MASK, 90, false));
assertThat(lat, Matchers.greaterThan(MERCATOR_BOUNDS));
assertTrue(Double.isFinite(latToSphericalMercator(90)));
}
{
// out of bounds values
final double lat = latToSphericalMercator(-randomDoubleBetween(GeoTileUtils.LATITUDE_MASK, 90, false));
assertThat(lat, Matchers.lessThan(-MERCATOR_BOUNDS));
assertTrue(Double.isFinite(latToSphericalMercator(-90)));
}
}

public void testRectangle() {
Expand Down