Skip to content

Instantly share code, notes, and snippets.

@thorwebdev
Last active August 29, 2015 14:10
Show Gist options
  • Save thorwebdev/b23844335ec70688ea4c to your computer and use it in GitHub Desktop.
Save thorwebdev/b23844335ec70688ea4c to your computer and use it in GitHub Desktop.
The process of testing for a point can easily be adapted to test our fences against polylines and polygons. In the case of polylines we query the index with the polyline’s bounding box and then test if the polyline actually crosses the returned fences.
@ApiMethod(name = "polyline", httpMethod = "post", path = "polyline")
public ArrayList < MyFence > queryPolyLine(@Named("group") String group, MyPolyLine polyline) {
ArrayList < MyFence > fences = new ArrayList < MyFence > ();
//Get the index from Memcache.
MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
GeometryFactory gf = new GeometryFactory();
STRtree index = (STRtree) syncCache.get(group); // read from cache
if (index != null) {
//Create coordinate array.
double[][] points = polyline.getCoordinates();
Coordinate[] coordinates = new Coordinate[points.length];
int i = 0;
for (double[] point: points) {
Coordinate coordinate = new Coordinate(point[0], point[1]);
coordinates[i++] = coordinate;
}
//Create polyline.
GeometryFactory fact = new GeometryFactory();
LineString linestring = new GeometryFactory().createLineString(coordinates);
List < MyPolygon > items = index.query(linestring.getEnvelopeInternal());
if (!items.isEmpty()) {
for (MyPolygon poly: items) {
if (linestring.crosses(poly) || poly.contains(linestring)) {
long id = poly.getID();
MyFence newFence = new MyFence();
newFence.setId(id);
fences.add(newFence);
}
}
}
} else {
try {
MyIndex.buildIndex(group);
} catch (IOException e) {
e.printStackTrace();
}
}
return fences;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment