String loc_expr = "distance(location, geopoint(" + userLatitude + ", " + userLongitude + "))";
// Build the SortOptions
SortOptions sortOptions = SortOptions.newBuilder()
.addSortExpression(SortExpression.newBuilder().setExpression(loc_expr).setDirection(SortExpression.SortDirection.ASCENDING).setDefaultValueNumeric(0))
.setLimit(200).build();
// Build the QueryOptions
QueryOptions options = QueryOptions.newBuilder().addExpressionToReturn(FieldExpression.newBuilder().setExpression(loc_expr).setName("distance")).setLimit(limit)
.setCursor(cursor).setSortOptions(sortOptions).build();
String queryString = loc_expr + " < " + searchRadius * 1000;
// Build the Query and run the search
Query query = Query.newBuilder().setOptions(options).build(queryString);
IndexSpec indexSpec = IndexSpec.newBuilder().setName("restaurants").build();
Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
Results<ScoredDocument> result = index.search(query);
if (result.getNumberFound() > 0) {
Collection<ScoredDocument> coll = result.getResults();
for (ScoredDocument sd : coll) {
Key<Restaurant> key = Key.create(String.valueOf(sd.getId()));
Restaurant rest = ofy().load().key(key).now();
Field f = sd.getExpressions().get(0);
log.info("distance in meter : " + f.getNumber());
}
}
我使用上面提到的代码来获取附近地区的餐馆。以下是我的观察: -
案例1:searchRadius = 0.5 km ---距离最大值= 0.9 km
案例2:searchRadius = 1 km ---距离最大值= 1.8 km
案例3:searchRadius = 2 km ---距离最大值= 2.8 km
案例4:searchRadius = 3 km ---距离最大值= 4.8 km
为什么我得到的距离值更多指定的半径?
注意: - 我不是靠自己计算距离。搜索API返回距离。