Using a comparison predicate with spatial data
Often, you want to compare one geographical location to another geographical location with a distance calculation. In particular, you desire to select entity instances having a property that pinpoints a location that is within a given distance of a reference location. To do this, use the appropriate withinDistance method in connection with an entity query.
The following code examples demonstrate how to use two varieties of the overloaded withinDistance method. The first code example uses the withinDistance method in connection with a simple entity query. This query selects those Address entity instances with a SpatialPoint property that is within 10 miles of a SpatialPoint constant representing San Mateo. The first code example is as follows:
uses gw.api.database.spatial.SpatialPoint
uses gw.api.database.Query
// Make a query on the Address entity.
var addressQuery = Query.make(Address)
// Define the location of the center point for the distance calculation.
var SAN_MATEO = new SpatialPoint(-122.300, 37.550)
// Specify the spatial point in the address instance and the maximum distance from the center.
addressQuery.withinDistance(Address.SPATIALPOINT_PROP.get(), SAN_MATEO, 10, UnitOfDistance.TC_MILE)
// Indicate that the query is an entity query by selecting all columns.
var result = addressQuery.select()
// Print the results of the query.
for (address in result) {
print(address)
}
The second code example uses the withinDistance method in connection with a more complex entity query that joins a primary entity type with a related entity type. This query joins the Person entity type, which has a PrimaryAddress property of type Address, with the Address entity type. The query then selects those Person entity instances with a PrimaryAddress.SpatialPoint property that is within 10 miles of a SpatialPoint constant representing San Mateo. The second code example is as follows:
uses gw.api.database.spatial.SpatialPoint
uses gw.api.database.Query
// Make a query on the Person entity.
var personQuery = Query.make(Person)
// Explicitly join the Address entity for the primary address to the Person.
var addressTable = personQuery.join(Person#PrimaryAddress)
// Define the location of the center point for the distance calculation.
var SAN_MATEO = new SpatialPoint(-122.300, 37.550)
// Specify the spatial point in the person's primary address and the maximum distance from the center.
addressTable.withinDistance(Address.SPATIALPOINT_PROP.get(), "Person.PrimaryAddress.SpatialPoint", SAN_MATEO, 10, UnitOfDistance.TC_MILE)
// Indicate that the query is an entity query by selecting all columns.
var result = personQuery.select()
// Print the results of the query.
for (person in result) {
print(person + ", " + person.PrimaryAddress)
}