Module: GitFit::Elevation::DemFetch

Defined in:
lib/git_fit/elevation/dem_fetch.rb

Constant Summary collapse

DEM_URL =
'https://api.opentopodata.org/v1/srtm30m'

Class Method Summary collapse

Class Method Details

.fetch_batch(slice, batch_idx, elevs, grid_key_fn) ⇒ Object



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
# File 'lib/git_fit/elevation/dem_fetch.rb', line 12

def fetch_batch(slice, batch_idx, elevs, grid_key_fn)
  qs = slice.map { |la, ln| "#{la},#{ln}" }.join('|')
  uri = URI("#{DEM_URL}?locations=#{qs.gsub(',', '%2C').gsub('|', '%7C')}")
  attempt = 0
  loop do
    res = Net::HTTP.get_response(uri)
    if res.code == '200'
      results = JSON.parse(res.body)['results']
      slice.each_with_index do |(lat, lng), i|
        elevs[grid_key_fn.call(lat, lng)] = results[i]['elevation'] if results[i]
      end
      break
    elsif res.code == '429'
      attempt += 1
      if attempt < 5
        delay = 2**attempt
        warn "DEM batch #{batch_idx}: rate limited, retrying in #{delay}s (attempt #{attempt})"
        sleep(delay)
      else
        warn "DEM batch #{batch_idx}: rate limited, giving up after #{attempt} attempts"
        break
      end
    else
      warn "DEM batch #{batch_idx} HTTP #{res.code}"
      break
    end
  rescue StandardError => e
    warn "DEM batch #{batch_idx}: #{e.message}"
    break
  end
end