2014-11-23 69 views
0

我試圖使用反向地理編碼與AsyncTask,但我不知道如何傳遞doInBackground()方法中的參數與緯度縱座標,然後執行AsyncTask。如何獲取doInBackground方法內的經緯度參數?

public static class NameAsyncTask extends AsyncTask<String, Void, String> { 
      Context mContext; 
      public GetAddressTask(Context context) { 
       super(); 
       mContext = context; 
      }  

      @Override 
      protected String doInBackground(String... arg0) { 
       Geocoder gc = new Geocoder(mContext, Locale.getDefault());   
       List<Address> list = null; 
       String city = "";   
       try { 
        list = gc.getFromLocation(lat, lng, 1);    
       } catch (IOException e) {    
        e.printStackTrace();     
       }    
       if (list != null && list.size() > 0) { 
        Address address = list.get(0); 
        city = String.format("%s, %s", address.getAdminArea(), address.getCountryName());        
       } 
       return city;    
      } 

      @Override 
      protected void onPostExecute(String city) {   
       tituloTxt.setText(city); 
      } 
    } 

回答

0

好了之後只有這樣才能通過座標。 先加協調,構造器LatLng(double latitude, double longitude)並傳遞參數:

lat = "-1.80"; 
lng = "-80.20"; 
LatLng latlng = new LatLng(lat, lng); 
new NameAsyncTask(context).execute(latlng); 

然後doInBackground方法中得到的參數:

@Override 
protected String doInBackground(LatLng... params) { 
    Geocoder gc = new Geocoder(mContext, Locale.getDefault());   
    List<Address> list = null; 
    String city = ""; 
    LatLng loc = params[0]; //Get all parameters: latitude and longitude   
    try { 
     list = gc.getFromLocation(loc.latitude, loc.longitude, 1); //get specific parameters     
    } catch (IOException e) {   
     e.printStackTrace();    
    } 
    if (list != null && list.size() > 0) { 
     Address address = list.get(0); 
     city = String.format("%s, %s", address.getAdminArea(), address.getCountryName()); 
     return city; 
    }else{ 
     return "City no found"; 
    }    
}