Search code examples
iosswiftgoogle-mapsgoogle-directions-apigoogle-polyline

How to draw route between multiple points in Google Maps?


I have implemented google maps in my app and there are several points i need to mark on the map. I was able to mark them with markers but the problem i am facing is trying to draw the path between all those points.

I tried using polyline but it just draws a straight line between point A and point B. I also tried google maps directionsAPI and it shows all the possible routes between A and B.

My question is how do i draw proper route between point A -> point B -> point C -> point D. I want the route to start at point A then go through B and C and end at point C. ( I do not want to see alternate routes)

Can anybody shed some light on how to do this?


Solution

  • You need to pass one or more (list of) | (pipe) separated lat longs (lat,longs) as waypoints to google's direction API. The overview polyline returned in response will contain a path from source to destination via all the way points you specified in your request.

    copying from Google's doc

    https://maps.googleapis.com/maps/api/directions/json?
    origin=sydney,au&destination=perth,au
    &waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
    &key=YOUR_API_KEY
    

    Read: https://developers.google.com/maps/documentation/directions/overview

    Scroll to waypoints section, its pretty straight forward :)

    Suggestion: If you are passing a list of | (pipe) separated lat longs ensure to properly encode comma (,) to %2C between lat and long values and ensure not to leave any space between them. Properly encode | as well.