如何使用地理编码器限制国家/地区?我使用这段代码,试图只看美国,但它返回意大利和其他国家的结果。
Geocoder geocoder = new Geocoder (getActivity(), Locale.US);
我有搜索,但我没有找到任何有用的东西。
答案 0 :(得分:4)
我最近通过简单地将", USA"
附加到用户输入的末尾来解决了这个问题。只需几行代码即可完美满足我们的需求:
public String restrictQueryToUsa(@NonNull String query) {
String suffix = ", USA";
return query.toUpperCase().endsWith( suffix ) ? query : query + suffix;
}
注意强>
我已经在各种输入上验证了这一点,包括:
答案 1 :(得分:1)
您应该在AutoCompleteTextView中应用自动完成适配器中实现getFilter方法,还应该实现“可过滤”
private class AutoCompleteAdapter extends ArrayAdapter<Address> implements
Filterable {
.....
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(
final CharSequence constraint) {
List<Address> addressList = null;
if (constraint != null) {
try {
addressList = mGeocoder.getFromLocationName(
(String) constraint, 5);
} catch (IOException e) {
}
}
if (addressList == null) {
addressList = new ArrayList<Address>();
}
final FilterResults filterResults = new FilterResults();
filterResults.values = addressList;
filterResults.count = addressList.size();
return filterResults;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(final CharSequence contraint,
final FilterResults results) {
clear();
for (Address address : (List<Address>) results.values) {
try {
/* HERE IS YOUR COUNTRY CODE / CONDITIONS TO FILTER THE SUGGESTED ADDRESS*/
if (address.getCountryCode().equals("US")) {
add(address);
}
} catch (Exception e) {
// TODO: handle exception
}
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
@Override
public CharSequence convertResultToString(
final Object resultValue) {
return resultValue == null ? ""
: createFormattedAddressFromAddress((Address) resultValue);
}
};
return myFilter;
}
}