无法从android中的经度和纬度获取地址

时间:2015-04-05 09:43:12

标签: android geocode

我试图从经度和纬度获取我的地址,但是当我尝试这样做时,它不起作用。它说 W / System.err:在logcat中的teamtreehouse.com.stromy.MainActivity.getCompleteAddressString(MainActivity.java:163)

这是我尝试过的方法

private   String getCompleteAddressString() {
    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();
            //     Log.w("My Current loction address", "" + strReturnedAddress.toString());

        } else {
            //    Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        //  Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}

我称之为

public void updateDisplay() {
    mLocation.setText(getCompleteAddressString());
}

在getCompleteAddressString()方法中,我使用了经度和纬度,我已经从另一个方法得到它并且它工作正常。两种方法都在运行主要活动。所有其他的东西都工作正常,除此之外,我该如何解决?这个错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

尝试这样:

        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        Address addr = null;
        try {
            addresses = gcd.getFromLocation(latitude, longitude, 1);
            if (addresses != null && addresses.size() > 0) {
                addr = addresses.get(0);
                String info = "Address is:  ";
                info += addr.getMaxAddressLineIndex() > 0 ? addr
                        .getAddressLine(0) : "";
                info = info + ", " + addr.getLocality() + ", "
                        + addr.getCountryName();
                Toast.makeText(getApplicationContext(), info,
                        Toast.LENGTH_LONG).show();
            } else
                Toast.makeText(getApplicationContext(),
                        "Address not found", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Address not found",
                    Toast.LENGTH_LONG).show();
        }