繁体   English   中英

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

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

我正在使用百度地图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

计算距离。

我该怎么办???

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

距离计算的百度文档可在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 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM