Last active
August 29, 2015 14:10
-
-
Save thorwebdev/ae7279e8d0e5317e4862 to your computer and use it in GitHub Desktop.
To speed up our geofencing queries we’re going to index our fences in an STR tree. The JTS library does most of the heavy lifting here, so we only need to fetch all our fences from Datastore, create a polygon object for each one and add the polygon’s bounding box to the index.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Get all fences of group from DataStore. | |
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); | |
Key fenceKey = KeyFactory.createKey("Geofence", group); | |
Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING); | |
List < Entity > fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()); | |
if (!fencesFromStore.isEmpty()) { | |
//Create STRTree-Index. | |
STRtree index = new STRtree(); | |
//Loop through the fences from DataStore. | |
for (Entity fenceFromStore: fencesFromStore) { | |
long id = (long) fenceFromStore.getProperty("id"); | |
Gson gson = new Gson(); | |
Text vText = (Text) fenceFromStore.getProperty("vertices"); | |
String vString = vText.getValue(); | |
double[][] vertices = gson.fromJson(vString, double[][].class); | |
//Store coordinates in an array. | |
Coordinate[] coordinates = new Coordinate[vertices.length]; | |
int i = 0; | |
for (double[] point: vertices) { | |
Coordinate coordinate = new Coordinate(point[0], point[1]); | |
coordinates[i++] = coordinate; | |
} | |
//Create polygon from the coordinates. | |
GeometryFactory fact = new GeometryFactory(); | |
LinearRing linear = new GeometryFactory().createLinearRing(coordinates); | |
MyPolygon polygon = new MyPolygon(linear, null, fact, id); | |
//Add polygon to index. | |
index.insert(polygon.getEnvelopeInternal(), polygon); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment