2012-06-10 74 views
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」時,我曾嘗試與不同座標也;沒有任何改變。我從日食中做了所有這些。

回答

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; 
    } 
} 
相關問題