如何使用地理编码器限制国家/地区?我使用此代码,试图只查看美国,但它返回来自意大利和其他国家的结果。
Geocoder geocoder = new Geocoder (getActivity(), Locale.US);
我有搜索,但我没有找到任何有用的东西。
我最近通过简单地附加", USA"
到用户输入的末尾解决了这个问题。只需几行代码即可完美满足我们的需求:
public String restrictQueryToUsa(@NonNull String query) {
String suffix = ", USA";
return query.toUpperCase().endsWith( suffix ) ? query : query + suffix;
}
注意
我已经在各种输入上验证了这一点,包括:
您应该在 AutoComplete 适配器中实现 getFilter 方法,该方法应用于您的 AutoCompleteTextView,您还应该实现“Filterable”
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;
}
}