1

I doing my android project about bus tracker in Uni campus. I need to draw a route from a bus stop to another bus stop and until back to origin bus stop.(There is about 20 bus stop in my Uni, need to draw route to let first user know the route of buses).

I managed to draw a path by following this tutorial here

In another tutorial , I found a blog which teaching draw path on google maps in 3 location. The sample code is

private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

private String getMapsApiDirectionsUrl() {
    String waypoints = "waypoints=optimize:true|"
            + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
            + "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
            + BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
            + WALL_STREET.longitude;

    String sensor = "sensor=false";
    String params = waypoints + "&" + sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + params;
    return url;
}

but I got an error which are:

java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|2.920114,101.775244||2.919726,101.771172|2.92234,101.769628&sensor=false
E/Background Task: java.lang.NullPointerException
E/ParserTask: errororg.json.JSONException: End of input at character 0 of

The tutorial of the blog is same with the link. Just different in

String waypoints = "waypoints=optimize:true|"
            + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
            + "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
            + BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
            + WALL_STREET.longitude;

and

/ Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;

// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;

Can anyone give me some tutorial or guidance in draw path in multiple markes? Thank in advance!

Community
  • 1
  • 1
noleavename
  • 83
  • 3
  • 15
  • May be your link is not valid, it says `Invalid request. Missing the 'origin' parameter.` Check if url is created well with `origin` and `destination` parameters. – ELITE Apr 06 '16 at 16:31
  • I think you need to define a origin as START, waypoints as Bus Stops and destination as FINISH route. Like this example: http://maps.googleapis.com/maps/api/directions/json?origin=40.722543,-73.998585&destination=40.7064,-74.0094&waypoints=optimize:true|40.7057,-73.9964| – Gorio Apr 06 '16 at 16:49
  • @ELITE i already try created well with origin and destination parameter, its work! – noleavename Apr 07 '16 at 02:29
  • @Gorio i trying your example, thank you! – noleavename Apr 07 '16 at 02:29
  • @Gorio, i not very familiar in JSON format, may you provide me the sample code in .java file? Thank in advance. – noleavename Apr 07 '16 at 02:39
  • I jest dint get it . you want a route that goes through more then 2 markers , and which are placed by you ? – Sagar Nayak Apr 07 '16 at 12:55

2 Answers2

7

First of all you need to fix your method

private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

private String getMapsApiDirectionsUrl() {
    String origin = "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude;
    String waypoints = "waypoints=optimize:true|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude + "|";
    String destination = "destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude;

    String sensor = "sensor=false";
    String params = origin + "&" + waypoints + "&"  + destination + "&" + sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + params;
    return url;
}

To get draw path i followed this answer https://stackoverflow.com/a/14702636/2697368

Once you get the JSON, just do it

public void drawPath(String result) {

    try {
        //Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        Polyline line = mMap.addPolyline(new PolylineOptions()
                .addAll(list)
                .width(12)
                .color(Color.parseColor("#05b1fb"))//Google maps blue color
                .geodesic(true)
        );

    } catch (JSONException e) {

    }
}

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;
}
Gorio
  • 1,606
  • 2
  • 19
  • 32
  • I managed to create the waypoint, but the path was skipped some of marker it went to the shortest distance to reach the destination. – noleavename Apr 07 '16 at 15:55
  • I don't think Directions Api skipped markers that you told him as waypoints or origin or destination. I think Directions optimize route with your points.. If you want an alternative route, see the documentation about how to obtain routes https://developers.google.com/maps/documentation/directions/intro?hl=pt-br#Routes – Gorio Apr 07 '16 at 16:14
  • Ya, thank for the explanation. If Direction was optimize the route it will became different route with my Uni campus bus's route, so i must be figure out add alternative route. – noleavename Apr 07 '16 at 16:42
  • may i ask you something extra? after i get the JSON can i save to sqlite ? because i had try my apps if my phone is offline my apps will force close after try to get JSON. So i think once i get the data i save to sqlite, next time when open the apps there is no need internet connection to draw path just retrieve from sqlite database. – noleavename Apr 09 '16 at 15:44
  • see my answer about sqlite here http://stackoverflow.com/questions/36461113/how-to-create-a-dynamically-table-with-data-from-sqlite-in-android/36483689#36483689 – Gorio Apr 10 '16 at 18:51
  • this is what I was looking for exactly – Parmendra Singh Jun 03 '18 at 11:11
  • Here " key "parameter is missing to add in getMapsApiDirectionsUrl – Brinda Rathod Oct 15 '18 at 11:42
0

Sometimes it happens when wrong url generated Using points.. May this function will help. It worked for me so I shared..

public static  String getMapsApiDirectionsUrl( LatLng start, LatLng End ) {
    String waypoints = "waypoints=optimize:true|"
            + start.latitude + "," + start.longitude
            + "|" + "|" +  End.latitude + ","
            + End.longitude;
    String OriDest = "origin="+start.latitude+","+start.longitude+"&destination="+End.latitude+","+End.longitude;

    String sensor = "sensor=false";
    String params = OriDest+"&%20"+waypoints + "&" + sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + params;
    return url;
}

Thanks.

Kush
  • 1,080
  • 11
  • 15