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

时间:2015-10-11 18:07:04

标签: java android google-maps geolocation 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;
}

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

1 个答案:

答案 0 :(得分:0)

您已拥有地址,您只需在其上调用getCountryName()方法即可。

我要做的是创建一个POJO类,以便您可以从方法返回地址和国家/地区:

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

然后,让你的方法调用返回MyLocation的实例,并在返回之前填充地址和国家:

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
    }