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 (65 lines) | stat: -rw-r--r-- 1,920 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
require 'geocoder/lookups/base'
require 'geocoder/results/opencagedata'

module Geocoder::Lookup
  class Opencagedata < Base

    def name
      "OpenCageData"
    end

    def required_api_key_parts
      ["key"]
    end

    private # ----------------------------------------------------------------

    def base_query_url(query)
      "#{protocol}://api.opencagedata.com/geocode/v1/json?"
    end

    def results(query)
      return [] unless doc = fetch_data(query)
      # return doc["results"]

      messages = doc['status']['message']
      case doc['status']['code']
      when 400 # Error with input
        raise_error(Geocoder::InvalidRequest, messages) ||
          Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
      when 403 # Key related error
        raise_error(Geocoder::InvalidApiKey, messages) ||
          Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
      when 402 # Quata Exceeded
          raise_error(Geocoder::OverQueryLimitError, messages) ||
          Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
      when 500 # Unknown error
        raise_error(Geocoder::Error, messages) ||
          Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
      end

      return doc["results"]
    end

    def query_url_params(query)
      params = {
        :q => query.sanitized_text,
        :key => configuration.api_key,
        :language => (query.language || configuration.language)
      }.merge(super)

      [:abbrv, :countrycode, :min_confidence, :no_dedupe, :no_annotations, :no_record, :limit].each do |option|
        unless (option_value = query.options[option]).nil?
          params[option] = option_value
        end
      end

      unless (bounds = query.options[:bounds]).nil?
        params[:bounds] = bounds.map{ |point| "%f,%f" % point }.join(',')
      end

      params
    end

  end
end