File: opencagedata.rb

package info (click to toggle)
ruby-geocoder 1.5.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 732 kB
  • sloc: ruby: 6,173; makefile: 3
file content (100 lines) | stat: -rw-r--r-- 2,104 bytes parent folder | download
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require 'geocoder/results/base'

module Geocoder::Result
  class Opencagedata < Base

    def poi
      %w[stadium bus_stop tram_stop].each do |key|
        return @data['components'][key] if @data['components'].key?(key)
      end
      return nil
    end

    def house_number
      @data['components']['house_number']
    end

    def address
      @data['formatted']
    end

    def street
      %w[road pedestrian highway].each do |key|
        return @data['components'][key] if @data['components'].key?(key)
      end
      return nil
    end

    def city
      %w[city town village hamlet].each do |key|
        return @data['components'][key] if @data['components'].key?(key)
      end
      return nil
    end

    def village
      @data['components']['village']
    end

    def state
      @data['components']['state']
    end

    def state_code
      @data['components']['state_code']
    end

    def postal_code
      @data['components']['postcode'].to_s
    end

    def county
      @data['components']['county']
    end

    def country
      @data['components']['country']
    end

    def country_code
      @data['components']['country_code']
    end

    def suburb
      @data['components']['suburb']
    end

    def coordinates
      [@data['geometry']['lat'].to_f, @data['geometry']['lng'].to_f]
    end

    def viewport
      bounds = @data['bounds'] || fail
      south, west = %w(lat lng).map { |i| bounds['southwest'][i] }
      north, east = %w(lat lng).map { |i| bounds['northeast'][i] }
      [south, west, north, east]
    end

    def time_zone
      # The OpenCage API documentation states that `annotations` is available
      # "when possible" https://geocoder.opencagedata.com/api#annotations
      @data
        .fetch('annotations', {})
        .fetch('timezone', {})
        .fetch('name', nil)
    end

    def self.response_attributes
      %w[boundingbox license 
        formatted stadium]
    end

    response_attributes.each do |a|
      unless method_defined?(a)
        define_method a do
          @data[a]
        end
      end
    end
  end
end