我正在编写一个Android应用程序来获取当前位置的城市名称,我得到了正确的纬度和经度,但我无法获得城市名称.这是我的代码:
// To get City-Name from coordinates
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: " + cityName;
editLocation.setText(s);
Run Code Online (Sandbox Code Playgroud)
小智 6
public String getLocationName(double lattitude, double longitude) {
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
10);
for (Address adrs : addresses) {
if (adrs != null) {
String city = adrs.getLocality();
if (city != null && !city.equals("")) {
cityName = city;
System.out.println("city :: " + cityName);
} else {
}
// // you should also try with addresses.get(0).toSring();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
Run Code Online (Sandbox Code Playgroud)
试试这个代码
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(yourLATITUDE, yourLONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
yourtextbox.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18933 次 |
| 最近记录: |