如何在doInBackground方法中获取纬度和经度参数



我尝试在AsyncTask中使用反向地理编码,但我不知道如何在方法doInBackground()中传递具有纬度纵向坐标的参数,然后执行AsyncTask。

    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);
            }
   }

之后,只需要这样做就可以传递坐标。首先将坐标添加到构造函数 LatLng(双纬度、双经度)并传递参数:

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";
    }               
}

最新更新