我怎样才能从LatLng获得地址

时间:2015-03-26 09:23:54

标签: android google-maps

我想从LatLng获取位置地址
我尝试了一些方法,但我没有得到答案,因为它看起来这个服务由谷歌关闭,所以当我使用以下代码时,我得到超时错误,是否有另一种解决方案?

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);

String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);

3 个答案:

答案 0 :(得分:0)

 private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
            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;
        }

尝试此功能,它工作正常。

答案 1 :(得分:0)

这工作正常,检查下面的代码并在try块中保留geocoder.getFromLocation()方法 Click Here

答案 2 :(得分:0)

试试这个

    public static String getAddressInString(Context context, LatLng latLng) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
        if (addresses != null && addresses.size() > 0) {
            return convertToString(addresses.get(0));
        } else {
            return "";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

public static String convertToString(Address obj) {
    String add = "";
    if (obj == null)
        return "";
    add = obj.getAddressLine(0);
    if (obj.getSubAdminArea() != null)
        add = add + "\n" + obj.getSubAdminArea();
    if (obj.getPostalCode() != null)
        add = add + " - " + obj.getPostalCode();
    if (obj.getAdminArea() != null)
        add = add + "\n" + obj.getAdminArea();
    if (obj.getCountryName() != null)
        add = add + "\n" + obj.getCountryName();
    return add;
}