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 @@ -34,6 +34,8 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* Used to work out the common values for areas in the examples.
Expand All @@ -55,6 +57,23 @@ public class Calculations {
private static final ThreadLocal<WKTReader> wktReader =
ThreadLocal.withInitial(WKTReader::new);

/**
* Parsed geometry and area in square meters for each WKT string seen,
* so that an area is only worked out once.
*/
private static final Map<String, CachedArea> wktAreas =
new ConcurrentHashMap<>();

private static class CachedArea {
final Geometry geo;
final double area;

CachedArea(Geometry geo, double area) {
this.geo = geo;
this.area = area;
}
}

/**
* A grid of latitude and longitude rectangles. Used to work out the
* geographic area using individual polygons no larger than 1 unit of
Expand All @@ -79,13 +98,29 @@ public static Result getAreas(
String wkt,
double latitude,
double longitude) throws Exception {
Geometry geo = wktReader.get().read(wkt);
if (geo != null) {
return getAreas(geo, latitude, longitude);
CachedArea cached = wktAreas.get(wkt);
if (cached == null) {
Geometry geo = wktReader.get().read(wkt);
cached = new CachedArea(geo, geo == null ? 0 : getAreas(geo));
wktAreas.put(wkt, cached);
}
if (cached.geo != null) {
return new Result(
(int) Math.round(cached.area / 1_000_000),
cached.geo.getNumGeometries(),
cached.geo.contains(cached.geo.getFactory().createPoint(
new Coordinate(longitude, latitude))));
}
return new Result(0, 0, false);
}

/**
* Number of WKT strings with a cached area.
*/
public static int getCachedWktCount() {
return wktAreas.size();
}

/**
* Returns the result for the geometric area, and geographic point.
* @param geo geometric area(s)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ public void testPolygonSplitByGridCell() throws Exception {
Calculations.getAreas(shape, 0, 0).getSquareKms());
}

@Test
public void testWktAreaIsCached() throws Exception {
String wkt = createRectangle(10, 51, 1).toText();

Calculations.getAreas(wkt, 0, 0);
int first = Calculations.getCachedWktCount();
Result again = Calculations.getAreas(wkt, 51.5, 10.5);

assertEquals(first, Calculations.getCachedWktCount());
assertTrue(again.getContains());
}

@Test
public void testContains() throws Exception {
Result result = Calculations.getAreas(
Expand Down
Loading