Search code examples
javascriptangularjsgoogle-maps-api-3directionsdistance-matrix

Connecting the given places using google maps api


Let say that a user wants to tour the US. When I list the places I want to travel with the origin and destination, I want the Google API to make a route in the shortest way possible.

For Eg: My Origin: Las Vegas, Destination: New York. And the places I want to tour are Texas, Utah and Ohio. So I need the Google to connect the shortest distance to visit these places like from Las Vegas -> Utah -> Texas -> Ohio -> New York

Is this possible with Google Maps API / Directions API / Directions API?

I have searched the documentation, and it has documentation for origin and destination connect not the list of places as mentioned above.


Solution

  • You can use Waypoints and the optimizeWaypoints option to render a route that includes your waypoints and arranges them in a more efficient order.

    By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order.

    https://developers.google.com/maps/documentation/javascript/directions#Waypoints

    Below is a fiddle to help you get started with using waypoints.

    JSFiddle demo