blob: 6ceb9c226951b3a26c6f9f1e30750b9f21e5eb56 (
plain)
| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 | module TomTom
  class Batch
    def initialize(connection)
      @connection = connection
    end
    def batch(way_costs)
      params = URI.encode_www_form({
        travelMode: 'bus',
        routeType: 'shortest'
      })
      batch_items = convert_way_costs(way_costs).map do |locations|
        {
          query: "/calculateRoute/#{locations}/json?#{params}"
        }
      end
      response = @connection.post do |req|
        req.url '/routing/1/batch/json'
        req.headers['Content-Type'] = 'application/json'
        req.body = {
          batchItems: batch_items
        }.to_json
      end
      extract_costs_to_way_costs!(
        way_costs,
        JSON.parse(response.body)
      )
    end
    def extract_costs_to_way_costs!(way_costs, batch_json)
      calculated_routes = batch_json['batchItems']
      calculated_routes.each_with_index do |route, i|
        next if route['statusCode'] != 200
        distance = route['response']['routes'][0]['summary']['lengthInMeters']
        time = route['response']['routes'][0]['summary']['travelTimeInSeconds']
        way_costs[i].distance = distance
        way_costs[i].time = time
      end
      way_costs
    end
    def convert_way_costs(way_costs)
      way_costs.map do |way_cost|
        "#{way_cost.departure.lat},#{way_cost.departure.lng}" \
        ":#{way_cost.arrival.lat},#{way_cost.arrival.lng}"
      end
    end
  end
end
 |