Android map:如何处理获取当前位置之间的顺序以及计算两个位置之间的距离

Android map:如何处理获取当前位置之间的顺序以及计算两个位置之间的距离,android,google-maps,android-asynctask,maps,distance,Android,Google Maps,Android Asynctask,Maps,Distance,我正在使用百度地图SDK获取我的当前位置,并成功获取纬度和经度。 我在服务器端存储了店铺位置(纬度和经度)[这是店铺位置,我将计算我当前位置和店铺位置之间的距离] 我需要做的是获取我当前的纬度和经度,存储在两个双类型变量中,然后从服务器端读取每个商店的信息,并计算距离,然后在TextView中按顺序显示距离 在这段代码中,我没有计算距离,只是在文本视图中显示纬度来测试这里是否有问题。 这是我的密码: package com.ecnu.vendingmachine.personal; impor

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

我需要做的是获取我当前的纬度和经度,存储在两个双类型变量中,然后从服务器端读取每个商店的信息,并计算距离,然后在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);
                }
            });
        }
    }

}
在第125126行中,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 -> " + String.valueOf(latitude));
Log.i(TAG, "longitude -> " + String.valueOf(longitude));
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
计算距离


我该怎么办?

在获取位置之前,正在运行
异步任务。你应该将你的异步任务移动到你的位置客户端的
onConnected
,这样你就可以从现在开始获得一个位置

百度距离计算文档可以在

在打开百度文档时,我还使用了Chrome中的自动翻译

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

我知道你的意思,但似乎没有onConnected方法,公共类MyLocationListener实现了BDLocationListener,它是实时的,每隔几秒钟就会获取一次位置。location客户端具有onConnected方法