Search code examples
google-mapsgoogle-maps-api-3directionsgoogle-polyline

Google Maps Directions API returns waypoints that don't make any sense, walk on water etc


I need to implement a sort of navigation feature in my app. I started diving into the Google Maps Directions API, where I expect to enter a point of origin and point of destination, and then get an optimized list of latlngs to use as a polyline. However, the line that I get is completely messy, goes zigzag, not snapping to sidewalk and even goes on the water and on buildings.

This is a sample request endpoint: https://maps.googleapis.com/maps/api/directions/json?origin=1017WT Oosteinde 11 Amsterdam&destination=Heineken Experience Amsterdam&key=AIzaSyAcojgYg79ssEaV_c1-7pRQpIKESob5Iz4

And in the response, there is the "overview_polyline" object containing the encoded polyline:

{
    overview_polyline: {
        points: "ylq~Hah|\\jDeAVKNt@VdBp@`Gl@jFDn@BhBOvD[rNIdHQjF"
    }
}

I took that polyline and decoded it using this website: https://developers.google.com/maps/documentation/utilities/polylineutility

And the result looks like this: enter image description here

Which doesn't make any sense. And that happens for any origin/destination that I try. Any idea if this is intended behavior (hard to believe), a bug or if there's a solution for this? Ideally the points will be on actual roads or sidewalk (depends on the travel mode) and not in non-accessible paths.


Solution

  • https://developers.google.com/maps/documentation/utilities/polylinealgorithm:

    "Note that the backslash is interpreted as an escape character within string literals. Any output of this utility should convert backslash characters to double-backslashes within string literals"

    So you just need to replace \\ with \.

    For instance,

    ylq~Hah|\\jDeAVKNt@VdBp@`Gl@jFDn@BhBOvD[rNIdHQjF

    should be

    ylq~Hah|\jDeAVKNt@VdBp@`Gl@jFDn@BhBOvD[rNIdHQjF