Search code examples
rubyroutesgoogle-directions-api

Google Distance - Set waypoints as lat,lng


I am using Google Direction Service from Ruby.

I have this object:

params = {
  origin: "37.88818,-4.77938",
  destination: "36.51903,-6.28014",
  waypoints: [
    {
      location:"Malaga",
      stopover:false
    }]
}

When I generate url all works fine:

uri = URI('http://maps.googleapis.com/maps/api/directions/json')
uri.query = URI.encode_www_form(params)

http://maps.googleapis.com/maps/api/directions/json?origin=37.88818%2C-4.77938&destination=36.51903%2C-6.28014&waypoints={%3Alocation%3D%3E%22Malaga%22}

But when I use (lat,lng) instead place name it returns error.

params = {
  origin: "37.88818,-4.77938",
  destination: "36.51903,-6.28014",
  waypoints: [
    {
      location:"36.72126,-4.42127",
      stopover:false
    }]
}

http://maps.googleapis.com/maps/api/directions/json?origin=37.88818%2C-4.77938&destination=36.51903%2C-6.28014&waypoints={%3Alocation%3D%3E%2236.72126%2C-4.42127%22}

How I can define waypoints using (lat,lng) format as origin and destination?


Solution

  • Based on my understanding of the API, below are my observations

    1. You are using JSON API of Google Maps API - the documentation is available here.
    2. The first URL you have shown as working is working by fluke. As per documentation,

      Waypoints are specified within the waypoints parameter and consist of one or more addresses or locations separated by the pipe (|) character.

      Hence, The query param needed for first example is origin=37.88818,-4.77938&destination=36.51903,-6.28014&waypoints=Malaga.

      The effective URL will be http://maps.googleapis.com/maps/api/directions/json?origin=37.88818,-4.77938&destination=36.51903,-6.28014&waypoints=Malaga.

    3. In order to use the latitude, longitude for waypoints, you can use origin=37.88818,-4.77938&destination=36.51903,-6.28014&waypoints=36.72126,-4.42127.

      The effective URL will be will be http://maps.googleapis.com/maps/api/directions/json?origin=37.88818,-4.77938&destination=36.51903,-6.28014&waypoints=36.72126,-4.42

    4. You cannot use nested Ruby Hash as input to URI#encode_www_form as it will produce improper query string. You need to simplify your params as shown below, so that it matches the requirements of the API

      params = { origin: "37.88818,-4.77938", destination: "36.51903,-6.28014", waypoints:"36.72126,-4.42" }