0

I have app which set multiple routes on the map. The problem is when I put two points in the map, he get the suggested routes but with one extra straight line.

I found a solution. I just get the main tag for polyline - overview_polyline

In the code are the new changes :)

pic multiple routes - alternatives=true - I set just one road

enter image description here

pic - if I set alternatives=false in xml link, the straight line disappears.

enter image description here

In the xml everything is fine. I looked in to the 2 xml files with alternatives=false and alternatives=true but there are identical.

enter image description here

link to XML file

Thanks in advance.

this code display the information:

 //Polyline
private class GetRouteTask extends AsyncTask<String, Void, String> {


    String response = "";


    @Override
    protected String doInBackground(String... urls) {
        //Get All Route values


        v2GetRouteDirection = new GMapV2Direction();

            document = v2GetRouteDirection.getDocument(latLngFrom, latLngTo, GMapV2Direction.MODE_DRIVING);


        response = "Success";
        return response;

    }

    @Override
    protected void onPostExecute(String result) {


        if(document != null){


                ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
                PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);


                for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));

                }



                // Adding route on the map
                map.addPolyline(rectLine);


        }


    }

}

this code get the tag information:

public class GMapV2Direction {



public GMapV2Direction(){}

public final static String MODE_DRIVING = "driving";
public final static String MODE_WALKING = "walking";


public static String error = null;


public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + start.latitude + "," + start.longitude
            + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=driving&alternatives=true";



    ////////////////

    //Set TimeOuts
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);



    try {

        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;



    }

    catch (ClientProtocolException e) {
        error = "some";
        e.printStackTrace();
    } catch (IOException e) {
        error = "some";
        e.printStackTrace();
    }

    catch (Exception e) {
        error = "some";
        e.printStackTrace();
    }


    return null;
}


public ArrayList<LatLng> getDirection (Document doc) {

    NodeList error = doc.getElementsByTagName("status");

    int p;
    Node error1 = null;
    //взема последнич елемент на таг
    for(p = 0;p<error.getLength();p++){
        error1 = error.item(p);
    }

    if(p==p){
        p--;
    }

    LatLng latLngZero = new LatLng(0.0, 0.0);

    ArrayList<LatLng> list = new ArrayList<LatLng>();
    list.add(latLngZero);


    ArrayList<LatLng> listGeopoints = null;


    if(error1.getFirstChild().getTextContent().equals("OK")) {

       //new

          NodeList routeTag,nl3;

            listGeopoints = new ArrayList<LatLng>();

            //get tag route
            routeTag = doc.getElementsByTagName("route");


            if (routeTag.getLength() > 0) {


                //get first eelemnt of route
                Element routeElement = (Element) routeTag.item(0);


                //get tag overview_polyline
                NodeList polylineList = routeElement.getElementsByTagName("overview_polyline");


                Node node1 = polylineList.item(0);

                nl3 = node1.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "points"));
                List<LatLng> arr = decodePoly(latNode.getTextContent());
                for (int j = 0; j < arr.size(); j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }


            }
   } 
     ////////////// 
     else{
        return list;

    }

    return listGeopoints;
}




private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
}

private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = new ArrayList<LatLng>();
    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 position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
  }
}
cross_flame
  • 840
  • 2
  • 11
  • 24

3 Answers3

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

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

  import android.util.Log;

 import com.google.android.gms.maps.model.LatLng;
 public class DirectionsJSONParser {

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

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

    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>>();
            List path1 = new ArrayList<ArrayList<HashMap<String,String>>>();

        // Log.d("legs",jLegs.toString());
            /** Traversing all legs */
            for(int j=0;j<jLegs.length();j++){
             HashMap<String, String> hm1 = new HashMap<String, String>();
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
               // Log.d("steps",jSteps.toString());
                /** 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);
                  //  Log.d("polyline",polyline.toString());
                    /** 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);
                      //  Log.d("lat", Double.toString(((LatLng)list.get(l)).latitude));
                      //  Log.d("lng", Double.toString(((LatLng)list.get(l)).longitude));
                    }

                }

                path1.add(path);

        }
            routes1.add(path1);
    }

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

return routes1;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    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;
}
}
Luke P V
  • 11
  • 2
0

Faced similar problem and soled it by using addall() method for polylineoptions object to draw line on map directly using array list of latlng's.

Cannot confirm but trying this code might help

Polyline

private class GetRouteTask extends AsyncTask<String, Void, String> {
    String response = "";

    @Override
    protected String doInBackground(String... urls) {
        //Get All Route values
        v2GetRouteDirection = new GMapV2Direction();
        document = v2GetRouteDirection.getDocument(latLngFrom, latLngTo, GMapV2Direction.MODE_DRIVING);
        response = "Success";
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        if(document != null){
            ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
            PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
            rectLine.addall(directionPoint);

            // Adding route on the map
            map.addPolyline(rectLine);
        }
    }

}
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
vamsikurre
  • 309
  • 3
  • 5
0
LatLng origin = new latlng(type your starting point latitude and longtitude);
LatLng dest = new latlng(type your ending point latitude and longtitude);

// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(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&alternatives=true&units=metric&mode=driving";
    //&alternatives=true&units=metric&mode=driving
    // 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;
}

/**
 * A method to download json data from url
 */
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();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {

    // Downloading data in non-ui thread
    @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]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

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

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/**
 * A class to parse the Google Places in JSON format
 */
private class ParserTask 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]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // 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;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";
        Log.d("resultsize", result.size() + "");
        int i = 0;
        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);
                    //  points = new ArrayList<LatLng>();
                    //                    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);
                    // Log.d("latlng", position.toString());
                    points.add(position);


                }
                //                lineOptions.addAll(points);
                //                lineOptions.width(5);
                //                lineOptions.color(Color.BLUE);
                //                map.addPolyline(lineOptions); 

            }
            // }
            if (i == 0) {
                PolylineOptions line1 = new PolylineOptions();
                line1.addAll(points);
                line1.width(5);
                line1.color(Color.RED);
                map.addPolyline(line1);
            } else if (i == 1) {
                PolylineOptions line2 = new PolylineOptions();

                line2.addAll(points);
                line2.width(5);
                line2.color(Color.BLUE);
                map.addPolyline(line2);
            } else if (i == 2) {
                PolylineOptions line3 = new PolylineOptions();

                line3.addAll(points);
                line3.width(5);
                line3.color(Color.GREEN);
                map.addPolyline(line3);
            }
            // Adding all the points in the route to LineOptions
            i++;
            // 
        }
        // Drawing polyline in the Google Map for the i-th route
        // map.addPolyline(lineOptions);
    }
}
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
Luke P V
  • 11
  • 2