从纬度/经度Android获取地址?

时间:2013-12-30 05:16:51

标签: java android geolocation

所以我尝试了很多不同的解决方案,如在线和StackOverflow上找到的,但我似乎无法让它工作。以下是我现在正在使用的内容,我在SO上发表了类似的帖子。我做错了什么?

public void getLocationName() {

    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(49.123124, -122.652404, 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", "Cannot get Address!");
    }
    Toast.makeText(getApplicationContext(), "Distance between two locations is: " + strAdd.toString(), Toast.LENGTH_LONG).show();
}

它总是抛出异常,所以它是我的坐标吗?

2 个答案:

答案 0 :(得分:0)

这是我的工作代码,试试吧。

 public void GiveResult() {
            Geocoder myLocation = new Geocoder(getApplicationContext(),
                    Locale.getDefault());
            try {
                List<Address> myList = myLocation.getFromLocation(latitude,
                        longitude, 1);

                if (myList != null && myList.size() > 0) {
                    Address address = myList.get(0);
                    result = address.getLocality();

                }
                Iterator<Address> it = myList.iterator();
                while (it.hasNext()) {

                    TextView tv = (TextView) findViewById(R.id.tv);
                    tv.setText("Data is" + it.next());

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

答案 1 :(得分:0)

试试这个,

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0); 
getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();