Android地图:如何处理获取当前位置和计算两个位置之间的距离之间的顺序

时间:2014-04-23 13:26:58

标签: android google-maps android-asynctask maps distance

我正在使用百度地图SDK来获取我当前的位置,并且成功获得经度和纬度。 我将商店位置(纬度和经度)存储在服务器端[这是商店位置,我将计算我当前位置和商店位置之间的距离]

我需要做的是获取我当前的纬度和经度,存储在两个双重类型变量中,然后从服务器端读取每个商店的信息,并计算距离,之后,在TextView中按顺序显示距离

在这段代码中,我没有计算距离,只是在TextView中显示纬度来测试这里是否存在问题。

这是我的代码:

package com.ecnu.vendingmachine.personal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.ecnu.vendingmachine.MyApplication;
import com.ecnu.vendingmachine.R;
import com.ecnu.vendingmachine.widgets.JSONParser;

public class CouponOrderActivity extends ListActivity {

    private static final String TAG = "CouponOrderActivity";
    private static final String TAG_SUCCESS = "success";

    private ListView listView;

    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    JSONArray vendingmachine = null;

    ArrayList<HashMap<String, String>> vendinglist;

    protected Context mContext;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private double latitude, longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vending_select);

        mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
        mLocationClient.setAccessKey("BpGYSXjAPeGID253M5UpDw0K");
        mLocationClient.registerLocationListener(myListener); // 注册监听函数

        setLocationOption();
        mLocationClient.start();// 开始定位

        Log.i(TAG, "latitude -> " + String.valueOf(latitude));
        Log.i(TAG, "longitude -> " + String.valueOf(longitude));

        vendinglist = new ArrayList<HashMap<String, String>>();
        mContext = getApplicationContext();
        listView = getListView();

        new get_all_vendingmachine().execute();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mLocationClient.stop();// 停止定位
    }

    /**
     * 设置相关参数
     */
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setIsNeedAddress(true); // 返回的定位结果包含地址信息
        option.setAddrType("all"); // 返回的定位结果包含地址信息
        option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
        option.disableCache(true); // 禁止启用缓存定位
        option.setPoiNumber(5); // 最多返回POI个数
        option.setPoiDistance(1000); // poi查询距离
        option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            latitude = location.getLatitude();
            longitude = location.getLongitude();

            Log.i(TAG,
                    "latitude in onReceiveLocation-> "
                            + String.valueOf(latitude));
            Log.i(TAG,
                    "longitude in onReceiveLocation-> "
                            + String.valueOf(longitude));

        }

        public void onReceivePoi(BDLocation poiLocation) {
            // 将在下个版本中去除poi功能
            if (poiLocation == null) {
                return;
            }
        }
    }

    class get_all_vendingmachine extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(CouponOrderActivity.this);
            pDialog.setMessage("loading vending machine..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // url to get all products list
            MyApplication myApplication = (MyApplication) getApplication();
            String url_all_vendingmachine = myApplication.getIP()
                    + "vendingmachine/vending_distance.php";

            JSONObject json = jsonParser.makeHttpRequest(
                    url_all_vendingmachine, "GET", params);

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // Getting Array of vendingmachine
                    vendingmachine = json.getJSONArray("vendings");
                    vendinglist.clear();
                    // looping through All vendingmachine
                    for (int i = 0; i < vendingmachine.length(); i++) {
                        JSONObject c = vendingmachine.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString("VMid");
                        String name = c.getString("Name");
                        String address = c.getString("Address");

                        Log.i(TAG,
                                "latitude in display -> "
                                        + String.valueOf(latitude));
                        Log.i(TAG,
                                "longitude in display-> "
                                        + String.valueOf(longitude));
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put("VMid", id);
                        map.put("Name", name);
                        map.put("Address", address);
                        map.put("distance", String.valueOf(latitude));

                        // adding HashList to ArrayList
                        vendinglist.add(map);
                    }

                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // updating listview
                    // HashMap<String, String>中的key
                    String[] from = { "Name", "Address", "VMid", "distance" };
                    // list_item.xml中对应的控件ID
                    int[] to = { R.id.vending_name, R.id.vending_address,
                            R.id.vending_id, R.id.distanceText };
                    SimpleAdapter adapter = new SimpleAdapter(mContext,
                            vendinglist, R.layout.vending_list, from, to);
                    listView.setAdapter(adapter);
                }
            });
        }
    }

}

根据logcat,

在第81,82行中,logcat为0

Log.i(TAG, "latitude -> " + String.valueOf(latitude));
Log.i(TAG, "longitude -> " + String.valueOf(longitude));

在第125,126行,logcat是我当前的位置,是我想要的

Log.i(TAG, "latitude in onReceiveLocation-> " + String.valueOf(latitude));
Log.i(TAG, "longitude in onReceiveLocation-> " + String.valueOf(longitude));

在第179,180行中,logcat为0

Log.i(TAG, "latitude in display -> " + String.valueOf(latitude));
Log.i(TAG, "longitude in display-> " + String.valueOf(longitude));

我认为这是关于执行顺序的问题,一旦调用onCreate方法,在获取当前位置之前,

new get_all_vendingmachine().execute(); 

正在运行。所以它只是使用

latitude, longitude = 0

计算距离。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

在您到达目的地之前,AsyncTask正在运行。您应该将异步任务移至位置客户端的onConnected,这样您就知道从现在起可以获取位置

答案 1 :(得分:0)

可以在以下位置找到用于距离计算的百度文档 http://lbsyun.baidu.com/index.php?title=androidsdk/guide/tool/calculation

打开百度文档时,我也在Chrome中使用自动翻译。

//Calculate the straight line distance between p1, p2, unit: meters  
DistanceUtil . getDistance ( p1 , p2 );