1

我有一个 Android 应用程序,我需要从 lat/long 获取地址。我使用了以下代码库:

Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null){
   try {
       address= geoCoder.getFromLocation(51.50, -0.12, 1);
       } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      }
      if (address.size()> 0){
        String postCode = address.get(0).getPostalCode();
        System.out.println(postCode);
      }
}

我还在清单文件中添加了以下内容

 uses-permission android:name="android.permission.INTERNET"  
 uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

但是每次我执行这个块时address.size()仍然是“0”,我也尝试过不同的坐标;什么都没有改变。我正在从 eclipse 做这一切。

4

1 回答 1

1

尝试这个:

private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
    Context mContext;

    public ReverseGeocodingTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected Void doInBackground(Location... params) {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

        Location loc = params[0];
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            // Format the first line of address (if available), city, and
            // country name.
            final String addressText = String.format(
                    "%s, %s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "", address.getLocality(),
                    address.getCountryName());

            // Update address field on UI.
            mHandler.post(new Runnable() {
                public void run() {
                    Toast.makeText(getBaseContext(),
                            addressText.toString(), Toast.LENGTH_SHORT)
                            .show();
                }
            });

        }
        return null;
    }
}
于 2012-07-02T07:52:16.377 回答