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

时间:2014-11-23 20:54:30

标签: android android-asynctask reverse-geocoding

我尝试使用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);
            }
   }

1 个答案:

答案 0 :(得分: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";
    }               
}