}
}
List<ResolvedLocation> cities = gazetteer.getClosestLocations(queryBuilder.build());
// initialize return objects components
ResolvedLocation finalCity = null;
ResolvedLocation finalState = null;
ResolvedLocation finalCountry = null;
// assume the most populous valid city is the correct one return
// note: this should be a reasonably safe assumption since we've attempted to enforce the
// notional hierarchy of given place names (e.g., city --> state/province/etc. --> country)
// and have therefore weeded out all other matches that don't fit this hierarchy
if (!cities.isEmpty()) {
finalCity = cities.get(0);
}
if (!states.isEmpty()) {
// if we couldn't find a valid city, just take the most populous valid state/province/etc.
if (finalCity == null) {
finalState = states.get(0);
} else {
for (ResolvedLocation state : states) {
// select the first state that is an ancestor of the selected city
if (finalCity.getGeoname().isDescendantOf(state.getGeoname())) {
finalState = state;
break;
}
}
}
}
if (!countries.isEmpty()) {
// use the selected city if available and the selected state if not to identify the selected country
ResolvedLocation best = finalCity != null ? finalCity : finalState;
// if neither city nor state was resolved, take the most populous valid country
if (best == null) {
finalCountry = countries.get(0);
} else {
for (ResolvedLocation country : countries) {
// select the first country that is an ancestor of the selected city or state
if (best.getGeoname().isDescendantOf(country.getGeoname())) {
finalCountry = country;
break;
}
}
}