谷歌地图,需要在TextView显示国家



我是新的谷歌地图,需要在一个textView显示用户的国家。目前我的应用程序正在显示纬度,经度和地址..现在我需要国家。

我声明了以下内容:

private LocationManager locationManager;
private Location myLocation;

在OnCreate

lblAddress = (TextView) findViewById(R.id.tvAddress);

获取我使用的地址;

private String getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try
    {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null)
        {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
            {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("n");
            }
            strAdd = strReturnedAddress.toString();
        }
    }
    catch (Exception e)
    {
        lblAddress.setText("Your address cannot be determined");
    }
    return strAdd;
}

现在我如何以同样的方式获得国家?

你已经有了地址,你可以在它上面调用getCountryName()方法。

我要做的是创建一个POJO类,这样你就可以从方法返回地址和国家:

class MyLocation {
    public String address;
    public String country;
}

然后,让你的方法调用返回一个MyLocation的实例,并在返回之前填充Address和Country:

private MyLocation getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    MyLocation myLocation = new MyLocation(); //added
    try
    {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null)
        {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");
            myLocation.country = returnedAddress.getCountryName(); //added
            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
            {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("n");
            }
            strAdd = strReturnedAddress.toString();
            myLocation.address = strAdd; //added
        }
    }
    catch (Exception e)
    {
        lblAddress.setText("Your address cannot be determined");
    }
    return myLocation; //modified
}

确保对返回值进行空检查。

    MyLocation loc = getCompleteAddressString(lat, lon, x);
    if (loc.address != null) {
        //use to populate Address TextView
    }
    if (loc.country != null) {
        //use to populate Country TextView
    }

最新更新