File: amap.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 (63 lines) | stat: -rw-r--r-- 1,648 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
require 'geocoder/lookups/base'
require "geocoder/results/amap"

module Geocoder::Lookup
  class Amap < Base

    def name
      "AMap"
    end

    def required_api_key_parts
      ["key"]
    end

    def supported_protocols
      [:http]
    end

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

    def base_query_url(query)
      path = query.reverse_geocode? ? 'regeo' : 'geo'
      "http://restapi.amap.com/v3/geocode/#{path}?"
    end

    def results(query, reverse = false)
      return [] unless doc = fetch_data(query)
      case [doc['status'], doc['info']]
      when ['1', 'OK']
        return doc['regeocodes'] unless doc['regeocodes'].blank?
        return [doc['regeocode']] unless doc['regeocode'].blank?
        return doc['geocodes'] unless doc['geocodes'].blank?
      when ['0', 'INVALID_USER_KEY']
        raise_error(Geocoder::InvalidApiKey, "invalid api key") ||
          warn("#{self.name} Geocoding API error: invalid api key.")
      else
        raise_error(Geocoder::Error, "server error.") ||
          warn("#{self.name} Geocoding API error: server error - [#{doc['info']}]")
      end
      return []
    end

    def query_url_params(query)
      params = {
        :key => configuration.api_key,
        :output => "json"
      }
      if query.reverse_geocode?
        params[:location] = revert_coordinates(query.text)
        params[:extensions] = "all"
        params[:coordsys] = "gps"
      else
        params[:address] = query.sanitized_text
      end
      params.merge(super)
    end

    def revert_coordinates(text)
      [text[1],text[0]].join(",")
    end

  end
end