Android Calculate Distance Traveled

后端 未结 2 1600
遥遥无期
遥遥无期 2020-12-18 15:02

I am currently working on an application focused around fitness. The basic I idea is to allow to people to track their speed,distance,time. So far I have managed to get spee

相关标签:
2条回答
  • 2020-12-18 15:19
     //*****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()); /Calendar 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) {
    
                                        }
                                    });
    

    // Changing message text color snackbar.setActionTextColor(Color.RED);

    // Changing action button text color View 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();
            }
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-18 15:36

    Try using this: http://googlemaps.github.io/android-maps-utils/javadoc/com/google/maps/android/SphericalUtil.html

    For each location you get, you create a LatLng and added it to a ArrayList. Then with this function it gets you the correct length:

    SphericalUtil.computeLength(latLngs);
    

    Gradle:

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

    EDIT: You have an Arraylist locations = new ArrayList globally. And in your "onLocationChanged" you add to the locations:

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

    Then when needed you do:

     for (Location loc :  locations){
         latLngs.add(new LatLng(loc.getLocation().getLat(), loc.getLocation().getLng()));
     }
     Double dist = SphericalUtil.computeLength(latLngs);
    
    0 讨论(0)
提交回复
热议问题