0

How can I get a polyline out of the Directions API JSON response?

Using the overview_polyline is not an option as it is only a smoothened version of the actual polyline.

I also tried getting the start and end location coordinates from the steps, however those will only give me a very inaccurate polyline, because they only contain a few coordiantes.

How can I get an accurate polyline out of the Directions response?

EDIT: Using @SaxonDruce answer, I can get accurate polylines however, they look like this:

enter image description here

Balázs Vincze
  • 3,550
  • 5
  • 29
  • 60

2 Answers2

0

Based on the sample response, you'll need something equivalent to:

response.routes[0].legs[0].steps[i].polyline.points

So, get the first route, then the first leg, then loop over the steps, then get the polyline, then get the points.

Saxon Druce
  • 17,406
  • 5
  • 50
  • 71
  • But this will give me the encoded polylines individually for every step, thus they would need to be drawn using multiple GMSPaths for each and every step. How can I combine them into one single GMSPath? Also, the lines are very jiggery and have sharp edges using this method! – Balázs Vincze Apr 20 '16 at 18:57
  • Your method works pretty well however, the only problem is that (due to drawing every polyline for the steps individually) the lines look very segmented and uneven (see edited answer). – Balázs Vincze Apr 20 '16 at 19:07
  • @BalázsVincze for the first issue, I found http://stackoverflow.com/a/24096653/148241 which has some code for combining multiple `GMSPath` objects into a single `GMSMutablePath`. – Saxon Druce Apr 21 '16 at 00:55
  • For the second issue, it looks like the encoded polyline rounds the coordinates to approx the nearest metre. See http://stackoverflow.com/questions/10207351/how-to-fix-losing-precision-when-encoding-polylines-for-google-maps and http://stackoverflow.com/questions/22394224/google-directions-api-encoded-polyline. I'm not sure if there's anything you can do about this to get a more accurate response from the Google API. Maybe you could filter out points which are close together? You'll still get segments, but they'll be longer and so maybe look better. – Saxon Druce Apr 21 '16 at 01:19
0

To add to saxon druce's answer, You can loop over all the steps of first leg and combine all the points to form a polyline.

List<LatLng> points = new ArrayList<>();
for (DirectionsStep step : legs[i].steps) {
    points.addAll(step.polyline.decodePath());
}
EncodedPolyline legPolyline = new EncodedPolyline(points);
manohar
  • 155
  • 1
  • 9