5

I'm currently developing an android google maps app help to get direction between 2 points on the map. I'm able to get the response from google maps service (Direction API) and draw polyline (Google Maps Android SDK) base on list of steps but the line is not snap to the road (curved line stick to road on the map), it's just straight line.

How can I draw polyline snap to road in Android app? I'm using Android Studio.

Here is my code to draw polyline.

void updateMapDirection() {
    Polyline newPolyline;
    PolylineOptions options = new PolylineOptions().width(3).color(Color.BLUE).geodesic(true);
    LatLng latLng = new LatLng(mLegs.get(0).getmStartLocation().getmLatitude(),
            mLegs.get(0).getmStartLocation().getmLongitude());
    options.add(latLng);
    for (WNStep i : mLegs.get(0).getmSteps()) {
        latLng = new LatLng(i.getmEndLocation().getmLatitude(), i.getmEndLocation().getmLongitude());
        options.add(latLng);
    }
    newPolyline = map.addPolyline(options);
}

Thanks for your help.

Andy
  • 2,374
  • 3
  • 17
  • 20
David Nguyen
  • 51
  • 1
  • 3
  • Not Android, but might help: http://stackoverflow.com/questions/10513360/polyline-snap-to-road-using-google-maps-api-v3 – Andy May 06 '15 at 18:24

1 Answers1

-1

This is how you can do it:

  • Once you have your JSON object as "result". Parse it, Also decode the polyline in form of a List.

    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);
    
  • Finally add Polyline Option by looping over the list and setting the properties of your polyline corresponding to the road you want to show as retrieved from Direction API on Google Maps.

    PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
    for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
    }
    line = myMap.addPolyline(options);
    
AniV
  • 3,997
  • 1
  • 12
  • 17