Android map: How to process the order between get current location and calculate the distance between two locations

StackOverflow https://stackoverflow.com/questions/23245806

Question

I'm using the Baidu map SDK to get my current location, and success get the latitude and longitude. I stored the store location(latitude and longitude) in server side[this is the shop location, i will calculate the distance between my current location and shop location]

What i need to do is get my current latitude and longitude, store in two double type variables, and then read every shop's information from server-side, and calculate the distance, after that, show the distance in order in a TextView

in this code, i didn't calculate the distance, just shows the latitude in the TextView to test whether there is a problem here.

here is my code:

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

}

according to the logcat,

in line 81, 82, the logcat is 0

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

in line 125,126, the logcat is my current location, is what i want

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

in line 179, 180, the logcat is 0

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

I think it's the problem about execute order, once the onCreate method be called, before getting my current location, the

new get_all_vendingmachine().execute(); 

is running. so it just use the

latitude, longitude = 0

to calculate the distance.

what should i do???

Was it helpful?

Solution

The AsyncTask is being run before you get your location. You should move your async task to your onConnected of your location client so you know you can get a location from now on

OTHER TIPS

Baidu documentation for distance calculation can be found at http://lbsyun.baidu.com/index.php?title=androidsdk/guide/tool/calculation

I also use auto translate in Chrome when opening the Baidu documentation.

//Calculate the straight line distance between p1, p2, unit: meters  
DistanceUtil . getDistance ( p1 , p2 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top