Android How to show route between markers on googlemaps

后端 未结 2 1386
梦如初夏
梦如初夏 2020-12-28 09:17

I\'m creating an App that will show the location of the user and put a marker to that position. After the user moves. The marker would be removed and a new marker would be c

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 09:57

    Here is the full code with minor tweaks. It's just a prettier.

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.util.Log;
    
    import com.eddress.R;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.PolylineOptions;
    
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    public class GoogleMapsPath {
    
        public GoogleMap map;
    
        public GoogleMapsPath(Activity context, GoogleMap map, LatLng origin, LatLng dest){
            this.map = map;
    
            String url = getDirectionsUrl(origin,dest);
            FetchUrl FetchUrl = new FetchUrl();
            FetchUrl.execute(url);
    
        }
    
        // Fetches data from url passed
        private class FetchUrl extends AsyncTask {
    
            @Override
            protected String doInBackground(String... url) {
    
                // For storing data from web service
                String data = "";
    
                try {
                    // Fetching the data from web service
                    data = downloadUrl(url[0]);
                    Log.d("Background Task data", data.toString());
                } catch (Exception e) {
                    Log.d("Background Task", e.toString());
                }
                return data;
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                ParserTask parserTask = new ParserTask();
    
                // Invokes the thread for parsing the JSON data
                parserTask.execute(result);
    
            }
        }
    
    
        private String downloadUrl(String strUrl) throws IOException {
            String data = "";
            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);
                }
    
                data = sb.toString();
                Log.d("downloadUrl", data.toString());
                br.close();
    
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            } finally {
                iStream.close();
                urlConnection.disconnect();
            }
            return data;
        }
    
    
        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;
    
            return url;
        }
    
    
        private class ParserTask extends AsyncTask>>> {
    
            // Parsing the data in non-ui thread
            @Override
            protected List>> doInBackground(String... jsonData) {
    
                JSONObject jObject;
                List>> routes = null;
    
                try {
                    jObject = new JSONObject(jsonData[0]);
                    Log.d("ParserTask",jsonData[0].toString());
                    DirectionsJSONParser parser = new DirectionsJSONParser();
                    Log.d("ParserTask", parser.toString());
    
                    // Starts parsing data
                    routes = parser.parse(jObject);
                    Log.d("ParserTask","Executing routes");
                    Log.d("ParserTask",routes.toString());
    
                } catch (Exception e) {
                    Log.d("ParserTask",e.toString());
                    e.printStackTrace();
                }
                return routes;
            }
    
            // Executes in UI thread, after the parsing process
            @Override
            protected void onPostExecute(List>> result) {
                ArrayList points;
                PolylineOptions lineOptions = null;
    
                // Traversing through all the routes
                for (int i = 0; i < result.size(); i++) {
                    points = new ArrayList<>();
                    lineOptions = new PolylineOptions();
    
                    // Fetching i-th route
                    List> path = result.get(i);
    
                    // Fetching all the points in i-th route
                    for (int j = 0; j < path.size(); j++) {
                        HashMap point = path.get(j);
    
                        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(8);
                    lineOptions.color(R.color.globalRedLight);
    
                    Log.d("onPostExecute","onPostExecute lineoptions decoded");
    
                }
    
                // Drawing polyline in the Google Map for the i-th route
                if(lineOptions != null) {
                    map.addPolyline(lineOptions);
                }
                else {
                    Log.d("onPostExecute","without Polylines drawn");
                }
            }
        }
    }
    

提交回复
热议问题