简体   繁体   English

如何在起点和目的地之间绘制多条路线,googlemaps api?

[英]How to draw more than one route, between origin and destination, googlemaps api?

I have a code to draw a route for the user.我有一个为用户绘制路线的代码。 But, I would like it to be drawn, the alternative routes, too.但是,我也希望绘制替代路线。 I changed the URL by passing the parameter alternatives=true and also the source code to bring the other routes.我通过传递参数alternatives=true以及引入其他路由的源代码来更改URL。 But, it's just being drawn, just one route.但是,它只是被绘制,只是一条路线。

I made these changes, based on the questions and answers, also here on the page.我根据问题和答案进行了这些更改,也在页面上。

Code:代码:

Map, receive the polylines and draw to user:映射,接收折线并绘制给用户:

     if (rota != null) {
                map.addPolyline(ApplicationUtils.getApplicationUtils().getPolylineOptions());


                //Adicionando ponto inicial
                CircleOptions circle = new CircleOptions().center(ultimaLocation);
                circle.fillColor(Color.DKGRAY);
                circle.radius(15); // Em metros
                map.addCircle(circle);
}

Calculate route:计算路线:

public void calculateRoute(LatLng origin, LatLng dest, String mode, RotaListener rotaListener) {
    this.rotaListener = rotaListener;
    try {
        // Getting URL to the Google Directions API
        String url = getDirectionsUrl(origem, destino, modo);

        Log.d(TAG, "URL DIRECTIONS = " + url);

        DownloadTask downloadTask = new DownloadTask();

        // Start downloading json data from Google Directions API
        downloadTask.execute(url);
    } catch (Exception e) {
        rotaListener.onFailure(e);
    }
}

private String getDirectionsUrl(LatLng origin, LatLng dest, String mode) {

    // 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";

    String str_mode = "mode=" + mode;

    // Building the parameters to the web service
    String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + str_mode +"&alternatives=true" ;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + MY_API_KEY;
    ;

    return url;
}

/**
 * A class to download data from Google Directions URL
 */
private class DownloadTask extends AsyncTask<String, Void, String> {

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {
        try {
            // For storing data from web service
            String data = "";

            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        } catch (Exception e) {
            rotaListener.onFailure(e);
            return "";
        }
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        try {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            if (rotaListener != null) {
                rotaListener.onRotaChanged(result);
                parserTask.execute(result);
            }
        } catch (Exception e) {
            rotaListener.onFailure(e);
        }
    }
}

/**
 * A class to parse the Google Directions in JSON format
 */
private class ParserTask extends AsyncTask<String, Integer, PolylineOptions> {

    // Parsing the data in non-ui thread
    @Override
    protected PolylineOptions doInBackground(String... jsonData) {
        try {
            JSONObject jObject;
            List<Rota> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();

                // Starts parsing data
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }

            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;

            // Traversing through all the routes
            for (int i = 0; i < routes.size(); i++) {
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = routes.get(i).Pontos;
                rotaListener.onTempoRotaChanged(routes.get(i).TempoEstimadoMin);

                // Fetching all the points in i-th route
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> 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(LARGURA_ROTA);
                lineOptions.color(COR_ROTA);
                lineOptions.geodesic(true);
                ApplicationUtils.getApplicationUtils().setPolylineOptions(lineOptions);
            }


            return lineOptions;
        } catch (Exception e) {
            rotaListener.onFailure(e);
            return null;
        }
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(PolylineOptions result) {
        // Drawing polyline in the Google Map for the i-th route
        try {
            if (rotaListener != null) {
                rotaListener.onInstrucoesRotaChanged(result);
                rotaListener = null;
            }
        } catch (Exception e) {
            rotaListener.onFailure(e);
        }
    }
}

public class DirectionsJSONParser {

    /**
     * Receives a JSONObject and returns a list of lists containing latitude and longitude
     */
    public List<Rota> parse(JSONObject jObject) {

        List<Rota> routes = new ArrayList<Rota>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        JSONObject jDuration = null;
        Rota rota;

        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<HashMap<String, String>>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
                    rota = new Rota();
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    if (jDuration != null) {
                        rota.TempoEstimadoMin = jDuration.getInt("value") / 60;
                    }
                    /** 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<String, String>();
                            hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
                            hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    rota.Pontos = path;
                    routes.add(rota);
                }
            }

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

If possible, I would like some help so that I can draw more than one route for the user.如果可能的话,我需要一些帮助,以便我可以为用户绘制不止一条路线。 Thank you!谢谢!

I think you should be doing this inside of the doInBackground task:我认为您应该在 doInBackground 任务中执行此操作:

for (int i = 0; i < routes.size(); i++) {
...
       // Adding all the points in the route to LineOptions
       lineOptions.addAll(points);
       lineOptions.width(LARGURA_ROTA);
       // Change the color with every new iteration of the route
       lineOptions.color(COR_ROTA);   
       lineOptions.geodesic(true);

       ApplicationUtils.getApplicationUtils().setPolylineOptions(lineOptions)  
  map.addPolyline(ApplicationUtils.getApplicationUtils().getPolylineOptions());

       lineOptions = null;
}

We're using slightly different libraries, but this is what my code looks like (encoded path is a string representing a group of lat/lons):我们使用的库略有不同,但这就是我的代码的样子(编码路径是一个表示一组纬度/经度的字符串):

       pathDynamic = new PolylineOptions().width(15).color(Color.RED);
        pathDynamic.addAll(decode(item.getEncodedPath()));
        if (mMap != null) {
            mMap.addPolyline(pathDynamic);
        }

I resolved by changing my parser class.我通过更改解析器类来解决。 Adding points in each iteration of FOR to specific variablesFOR每次迭代中将点添加到特定变量

private class ParserTask1 extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> {

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

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

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser1 parser = new DirectionsJSONParser1();

            // Starts parsing data
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

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

        PolylineOptions lineOptions1 = null;


        List<LatLng> aline1 = new ArrayList<LatLng>();
        List<LatLng> aline2 = new ArrayList<LatLng>();
        List<LatLng> aline3 = new ArrayList<LatLng>();
        Rota rota = new Rota();
        List<HashMap<String, String>> rotaNumero = new ArrayList<>();
        HashMap<String, String> pointNumber = null;

        if (result != null) {
            int i = 0;
            Log.d(SHETTY, "onPostExecute: result size " + result.size());

            while (i < result.size()) {

                //  for(int i=0;i<result.size();i++){
                //result.size()
                //int g= i-1;
                points = new ArrayList<LatLng>();
                // lineOptions = new PolylineOptions();
                // if(i==1){

                // }else{
                List<List<HashMap<String, String>>> path1 = result.get(i);

                for (int s = 0; s < path1.size(); s++) {
                    Log.d("pathsize1", path1.size() + "");

                    // Fetching i-th route
                    List<HashMap<String, String>> path = path1.get(s);
                    Log.d("pathsize", path.size() + "");
                    // Fetching all the points in i-th route

                    for (int j = 0; j < path.size(); j++) {
                        lineOptions1 = new PolylineOptions();
                        HashMap<String, String> point = path.get(j);
                        pointNumber = path.get(j);
                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng);
                        // Log.d("latlng", position.toString());
                        points.add(position);


                    }

                }

                if (i == 0) {
                    rotaNumero.add(pointNumber);
                    ApplicationUtils.getApplicationUtils().setPoints(rotaNumero);
                    aline1.addAll(points);
                    ApplicationUtils.getApplicationUtils().setAline1(aline1);
                    rotaNumero.clear();
                } else if (i == 1) {
                    rotaNumero.add(pointNumber);
                    ApplicationUtils.getApplicationUtils().setPoints2(rotaNumero);
                    aline2.addAll(points);
                    ApplicationUtils.getApplicationUtils().setAline2(aline2);
                    rotaNumero.clear();
                } else if (i == 2) {
                    rotaNumero.add(pointNumber);
                    ApplicationUtils.getApplicationUtils().setPoints2(rotaNumero);
                    aline3.addAll(points);
                    ApplicationUtils.getApplicationUtils().setAline3(aline3);
                    rotaNumero.clear();
                }
                // Adding all the points in the route to LineOptions
                i++;

            }

            try {
                if (rotaListener != null) {
                    rotaListener.onInstrucoesRotaChanged(lineOptions.addAll(ApplicationUtils.getApplicationUtils().getAline1()));
                    rotaListener = null;
                }
            } catch (Exception e) {
                rotaListener.onFailure(e);
            }
        }

    }

}

After inserting the points, in my class where I have the map, I draw the routes.插入点后,在我有地图的班级中,我绘制路线。

private void drawRoutes() {


        line1 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.btn_map_inserir_pressed));
        line2 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.verde_novo));
        line3 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.azul));

        line1.addAll(ApplicationUtils.getApplicationUtils().getAline1());
        map.addPolyline(line1);

        if (ApplicationUtils.getApplicationUtils().getAline2() != null) {
            line2.addAll(ApplicationUtils.getApplicationUtils().getAline2());
            map.addPolyline(line2);
        }
        if (ApplicationUtils.getApplicationUtils().getAline3() != null) {
            line3.addAll(ApplicationUtils.getApplicationUtils().getAline3());
            map.addPolyline(line3);
        }

    }

暂无
暂无

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

相关问题 我想使用静态Google Maps API在起点和终点之间画一条直线 - I want to draw staight line between origin and destination using static google maps api 如何从标记到另一个标记绘制路线方向? Googlemaps v2 Android - How to draw route directions from a marker to another one ? Googlemaps v2 Android Android如何在googlemaps上显示标记之间的路线 - Android How to show route between markers on googlemaps 如何在Android的Google地图上绘制两个以上的路线? - How to draw route more than two points on Google map in android? Android:在GoogleMaps上的街道上寻找2个或更多点之间最快的路线 - Android: find fastest route between 2 or more points depeding on streets in GoogleMaps 如何通过 GoogleMaps 上的多个点绘制从 A 到 B 的路线? - How to draw route from A to B through multiple points on GoogleMaps? GoogleMaps API(Android)–在标记的边缘之间绘制折线,并通过缩放调整 - GoogleMaps API (Android) – Draw PolyLine between the edges of Markers adjusting with Zoom Android:如何绘制路线方向谷歌地图API V2从当前位置到目的地 - Android: How to draw route directions google maps API V2 from current location to destination 使用Google API绘制从我的位置到目的地位置的路线 - Draw Route from my location to destination location using google API Google Maps API计算起点和终点之间的确切距离 - Google Maps API to calculate exact distance between origin and destination
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM