Android计算行进距离

时间:2017-01-18 12:33:11

标签: android

我目前正在开发一个专注于健身的应用程序。我的基本想法是让人们跟踪他们的速度,距离和时间。到目前为止,我已经设法通过使用位置管理器getSpeed()来提高速度。我想知道如何获得旅行的距离? 我寻找了一些样本,但对我来说有点困惑,因为我刚刚开始使用android。 我将不胜感激任何帮助或建议,谢谢

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

    start = (Button) findViewById(R.id.btnStart);
    speed = (TextView)findViewById(R.id.txtSpeed);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);



    //initialize location listener
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            getSpeed(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }

        //get the speed from the given location updates
        public void getSpeed(Location location) {
            currentSpeed = (location.getSpeed()*3600/1000);
            String convertedSpeed = String.format("%.2f",currentSpeed);
            speed.setText(convertedSpeed + "Km/h");
        }

        public void getDistance(Location location){

        }

    };

2 个答案:

答案 0 :(得分:4)

尝试使用此: http://googlemaps.github.io/android-maps-utils/javadoc/com/google/maps/android/SphericalUtil.html

对于您获得的每个位置,您创建一个LatLng并将其添加到ArrayList。 然后使用此功能可以获得正确的长度:

SphericalUtil.computeLength(latLngs);

摇篮:

 dependencies {
compile 'com.google.maps.android:android-maps-utils:0.4+'
}

编辑: 你有一个全局的Arraylist locations = new ArrayList。 在你的" onLocationChanged"你添加到位置:

  @Override
    public void onLocationChanged(Location location) {
        locations.add(location);
    }

然后在需要时你做:

 for (Location loc :  locations){
     latLngs.add(new LatLng(loc.getLocation().getLat(), loc.getLocation().getLng()));
 }
 Double dist = SphericalUtil.computeLength(latLngs);

答案 1 :(得分:0)

 //*****this is for log in and gcm reg id passsing in back end
private class communicate_server_for_get_2_position_duration extends AsyncTask<String, Void, String> {

    static final String TAG = "rvms";

    Context getcontext;
    String lat1 = null, lng1 = null, lat2 = null, lng2 = null;

    String getcontent_for_validate, content;

    public communicate_server_for_get_2_position_duration(Context context, double lat, double lng, double lat2, double lng2) {
        getcontext = context;
        lat1 = String.valueOf(lat);
        lng1 = String.valueOf(lng);
        this.lat2 = String.valueOf(lat2);
        this.lng2 = String.valueOf(lng2);
    }


    @Override
    protected void onPreExecute() {

        // TODO Auto-generated method stub
        super.onPreExecute();

        try {

        } catch (Exception e) {
            finish();
        }

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        BufferedReader reader;
        String url_data = null;
        try {
            url_data = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + lat1 + "," + lng1 + "&destinations=" + lat2 + "," + lng2 + "&mode=driving&language=en-EN";
            url_data = url_data.replace("\n", "%20");
            url_data = url_data.replace(" ", "%20");
            url_data = url_data.replace("'", "%20");
        } catch (Exception e) {

        }
        Log.i("pavan", "url" + url_data);
        try {
            URL url = new URL(url_data);
            URLConnection conection = url.openConnection();
            conection.setConnectTimeout(5000);
            conection.setDoOutput(true);


            reader = new BufferedReader(new InputStreamReader(conection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                result.append(line + "");

            }
            content = result.toString();
            System.out.print(result);
            System.out.println(content);
            getcontent_for_validate = content;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;


    }

    @Override
    protected void onPostExecute(String result) {
        JSONObject jsonobj;
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
        String distance = null, duration = null;
        if (result != null) {
            if (content.equals("failure")) {


            } else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
                JSONObject location1, location2;
                String location_string1 = null;
                try {
                    JSONObject ret = new JSONObject(getcontent_for_validate);
                    // Toast.makeText(getApplicationContext(),"this is get content"+jsonobj.toString(),Toast.LENGTH_SHORT).show();
                    //  System.out.println("this is get content"+jsonobj.toString());


                    try {
                        location1 = ret.getJSONArray("rows").getJSONObject(0);
                        location2 = location1.getJSONArray("elements").getJSONObject(0);


                        JSONObject get_distance = location2.getJSONObject("distance");
                        distance = get_distance.getString("text");

                        JSONObject get_duration = location2.getJSONObject("duration");
                        duration = get_duration.getString("text");

                        Log.d("test", "formattted address:" + location_string1);
                    } catch (JSONException e1) {
                        e1.printStackTrace();

                    }
                } catch (JSONException e1) {
                    e1.printStackTrace();

                }
                try {
                    if (key_for_intent_data_from.equals("from current location")) {

// fabBtn.show();                             // String formattedDate = new SimpleDateFormat(“yyyy-MM-dd hh:mm aa”)。format(Calendar.getInstance()。getTime());                             / 日历c = Calendar.getInstance();                             SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss aa”);                             String formattedDate = sdf.format(c.getTime()); /                             / * TimeZone utc = TimeZone.getTimeZone(“etc / UTC”);                             DateFormat inputFormat = new SimpleDateFormat(“dd MMM,yyyy HH:mm”,Locale.US);                             inputFormat.setTimeZone(UTC);                             DateFormat outputFormat = new SimpleDateFormat(“dd MMM,yyyy hh:mm aa”,Locale.US);                             outputFormat.setTimeZone(UTC);

                        Date date = inputFormat.parse(input);
                        String output = outputFormat.format(date);*/

                        // fabBtn.setVisibility(View.VISIBLE);


                        //currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new java.util.Date());

                        duration_text_view.setText("\nPresent DATE/TIME: " + currentDateTimeString + "\nDevice DATE/TIME: " + deviceTime + "\nLOCATION: " + distance + " from your location point.");
                    } else {
                        String snackbar_data = null;


                        snackbar_data = "Date/Time:" + deviceTime + "\nLocation:" + distance + " from your location point.";

                        View parentLayout = findViewById(R.id.map);
                        Snackbar snackbar = Snackbar
                                .make(parentLayout, snackbar_data, Snackbar.LENGTH_INDEFINITE)
                                .setAction("CLOSE", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {

                                    }
                                });

//更改消息文本颜色                             snackbar.setActionTextColor(Color.RED);

//更改操作按钮文字颜色                             查看sbView = snackbar.getView();                             TextView textView =(TextView)sbView.findViewById(android.support.design.R.id.snackbar_text);                             textView.setTextColor(Color.WHITE);                             textView.setLines(5);                             snackbar.show();

                    }
                } catch (Exception e) {

                }

            }


        } else {

            Toast.makeText(getcontext, "Check net connection", Toast.LENGTH_LONG).show();
        }

    }

}