我正在尝试按位置获取用户所在的城市,但我无法仅获取该城市!
我几乎尝试了所有我认为的事情,但似乎没有任何效果,或者实际上,唯一可以按位置获取用户信息的方法是“ getAddressLine(0)”。
下面是代码
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
String city="unknown";
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
} catch (Exception e) {
Log.d(TAG, "getAddress failed: " + e.getMessage());
e.printStackTrace();
return "Couldn't find city!";
}
if(addresses != null && addresses.size() > 0) {
city = addresses.get(0).getAddressLine(0); // Returns full address!
// city = addresses.get(0).getLocality(); // Returns only an empty string " ".
}
return city;
所以,我想知道如何仅获得CITY而不能获得完整地址。另外,为什么“ getLocality()”返回一个无用的空字符串?
我仍然想知道为什么getLocality()不起作用,
但是我创建了一个临时解决方案,如下代码:
if(addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // StreetAddress -> StreetAddress Number -> Postal Code -> City -> Country
String[] splitAddress = address.split(" "); // Splits address where there is a space, creating array with 5 index. Index 4 should be CITY!
city=splitAddress[4].substring(0,splitAddress[4].length()-1); // Saves city into city-string, and removes a comma from the getAddressLine(0)!
Log.d("SplittedAddress", Arrays.toString(splitAddress));
}
答案 0 :(得分:0)
如果您想要城市,请尝试:
String city = addresses.get(0).getAddressLine(1);
答案 1 :(得分:0)
Adress.get(1).getAddressLine(0);