如何使用Google Directions api获得距离?

时间:2019-04-29 16:07:15

标签: java android distance

我是编程的初学者。     我写了以下代码(在网上看),但我不明白如何才能使它出现在Toast中。     谁能帮我吗?

我创建了一个接口,在其中放置了代码,以便从url中获取所需的一切,我可以接收JSON格式的答案,但是我不明白如何从响应中接收的JSON中提取距离< / p>

    import com.google.android.gms.maps.model.LatLng;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    public class DataParser {
        public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

            List<List<HashMap<String, String>>> routes = new ArrayList<>();
            JSONArray jRoutes;
            JSONArray jLegs;
            JSONArray jSteps;

            try {
                jRoutes = jObject.getJSONArray("routes");
                /** Traversing all routes */
                for (int i = 0; i < jRoutes.length(); i++) {
                    jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                    List path = new ArrayList<>();
                    /** Traversing all legs */
                    for (int j = 0; j < jLegs.length(); j++) {

                        jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                        /** Traversing all steps */
                        for (int k = 0; k < jSteps.length(); k++) {
                            String polyline = "";
                            polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                            List<LatLng> list = decodePoly(polyline);

                            /** Traversing all points */
                            for (int l = 0; l < list.size(); l++) {
                                HashMap<String, String> hm = new HashMap<>();
                                hm.put("lat", Double.toString((list.get(l)).latitude));
                                hm.put("lng", Double.toString((list.get(l)).longitude));
                                path.add(hm);
                            }
                        }
                        routes.add(path);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
            }
            return routes;
        }

        /**
         * Method to decode polyline point
         */
        private List<LatLng> decodePoly(String encoded) {

            List<LatLng> poly = new ArrayList<>();
            int index = 0, len = encoded.length();
            int lat = 0, lng = 0;

            while (index < len) {
                int b, shift = 0, result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lat += dlat;

                shift = 0;
                result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lng += dlng;

                LatLng p = new LatLng((((double) lat / 1E5)),
                        (((double) lng / 1E5)));
                poly.add(p);
            }

            return poly;
        }
    }

    import android.content.Context;
    import android.graphics.Color;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.Toast;

    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.PolylineOptions;

    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    public class PointsParser extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
        TaskLoadedCallback taskCallback;
        String directionMode = "walking";
        MainActivity mainActivity = new MainActivity();

        public PointsParser(Context mContext, String directionMode) {
            this.taskCallback = (TaskLoadedCallback) mContext;
            this.directionMode = directionMode;
        }

        // Parsing the data in non-ui thread
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                Log.d("mylog", jsonData[0].toString());
                DataParser parser = new DataParser();
                Log.d("mylog", parser.toString());

                // Starts parsing data
                routes = parser.parse(jObject);
    //            Log.d("routes-->",routes.toString());
                Log.d("mylog", "Executing routes");
                Log.d("mylog", routes.toString());

            } catch (Exception e) {
                Log.d("mylog", e.toString());
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points;
            PolylineOptions lineOptions = null;
            String distance = "";
            String duration = "";

            if(result.size()<1){
               //Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }

            // Traversing through all the routes
               Log.d("result --> ", result.toString());

                for (int i = 0; i < result.size(); i++) {
                    points = new ArrayList<>();
                    lineOptions = new PolylineOptions();
                    // Fetching i-th route
                    List<HashMap<String, String>> path = result.get(i);
                    // Fetching all the points in i-th route
                    for (int j = 0; j < path.size(); j++) {
                        HashMap<String, String> point = path.get(j);
                        if(j==0){    // Get distance from the list
                            distance = (String)point.get("distance");
                            continue;
                        }else if(j==1){ // Get duration from the list
                            duration = (String)point.get("duration");
                            continue;
                        }

                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng);
                        points.add(position);
                    }
                    // Adding all the points in the route to LineOptions
                    lineOptions.addAll(points);
                    lineOptions.width(20);
                    lineOptions.color(Color.BLUE);
                    Log.d("mylog", "onPostExecute lineoptions decoded");
                }

                // Drawing polyline in the Google Map for the i-th route
                if (lineOptions != null) {
                    //mMap.addPolyline(lineOptions);
                    mainActivity.getToast(distance,duration);
                    taskCallback.onTaskDone(lineOptions);

                } else {
                    Log.d("mylog", "without Polylines drawn");
                }
         }
    }

    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class FetchURL extends AsyncTask<String, Void, String> {
        Context mContext;
        String directionMode = "walking";

        public FetchURL(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        protected String doInBackground(String... strings) {
            // For storing data from web service
            String data = "";
            directionMode = "walking";
            try {
                // Fetching the data from web service
                data = downloadUrl(strings[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            PointsParser parserTask = new PointsParser(mContext, directionMode);
            // Invokes the thread for parsing the JSON data
            parserTask.execute(s);
        }

        private String downloadUrl(String strUrl) throws IOException {
            String data = "";
            boolean flag = false;
            String distance ="";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(strUrl);
                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();
                // Connecting to url
                urlConnection.connect();
                // Reading data from url
                iStream = urlConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                StringBuffer sb = new StringBuffer();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    String[] values = line.split(":");
                    Log.d("values key--->", values[0]);
                    Log.d("values value--->", values[1]);
                }
                data = sb.toString();
                Log.d("mylog", "Downloaded URL: " + data.toString());

                br.close();
            } catch (Exception e) {
                Log.d("mylog", "Exception downloading URL: " + e.toString());
            } finally {
                iStream.close();
                urlConnection.disconnect();
            }
            return data;
        }
    }

这是主要的:

    import android.Manifest;
    import android.support.v4.app.ActivityCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.google.android.gms.maps.model.Polyline;
    import com.google.android.gms.maps.model.PolylineOptions;

    public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, TaskLoadedCallback {

        private GoogleMap map;
        private MarkerOptions start, finish;
        private Polyline polyline;
        Button position;

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

            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
            position = findViewById(R.id.position);
            MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFrag);
            mapFragment.getMapAsync(this);

            final LatLng init = new LatLng(45.6736241,12.1466323);
            final LatLng fin = new LatLng(45.60223647212919,12.241125547197981);

            start = new MarkerOptions().position(init).title("Start");
            finish = new MarkerOptions().position(fin).title("Finish");

            position.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    new FetchURL(MainActivity.this).execute(getUrl(start.getPosition(), finish.getPosition(), "walking"));
                }
            });
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
            map.getUiSettings().setZoomControlsEnabled(true);
            map.setMyLocationEnabled(true);
            map.addMarker(start);
            map.addMarker(finish);
            // per settare vista satelitte
            // map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        }

        private String getUrl(LatLng origin, LatLng destination, String mode){
            String start = "origin=" + origin.latitude + "," + origin.longitude;
            String finish = "destination=" + destination.latitude + "," + destination.longitude;
            String modeType = "mode=" + mode;
            String parameter = start + "&" + finish + "&" + modeType;
            String output = "json";
            String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameter +"&key=" + getString(R.string.API_key);
            Log.d("url-->", url);
            return url;
        }

        private String getDirectionsUrl(LatLng origin,LatLng dest){

            // Origin of route
            String str_origin = "origin="+origin.latitude+","+origin.longitude;
            // Destination of route
            String str_dest = "destination="+dest.latitude+","+dest.longitude;
            // Sensor enabled
            String sensor = "sensor=false";
            // Building the parameters to the web service
            String parameters = str_origin+"&"+str_dest+"&"+sensor;
            // Output format
            String output = "json";
            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters + "&key=" + getString(R.string.API_key);;

            return url;
        }

        @Override
        public void onTaskDone(Object... values) {
            if(polyline != null)
                polyline.remove();
            //Toast.makeText(getApplicationContext(), "Distance" + values[1], Toast.LENGTH_LONG).show();
            polyline = map.addPolyline((PolylineOptions) values[0]);
        }

        @Override
        public void onTaskDone(PolylineOptions polylineOptions, String distance, String duration) {

        }

        public void getToast(/*PolylineOptions polylineOptions*/ String distance, String duration) {
            //if(polylineOptions != null)
              //  polyline.remove();
            Toast.makeText(getApplicationContext(), "Distance" + distance, Toast.LENGTH_LONG).show();
            //polyline = map.addPolyline((PolylineOptions) polylineOptions);
        }


        @Override
        public void onPointerCaptureChanged(boolean hasCapture) {

        }
    }

0 个答案:

没有答案