Module: BaiduApi::Geocoding::V2::Geocoder

Extended by:
Geocoder
Included in:
Geocoder
Defined in:
lib/baidu_api/geocoding/v2/geocoder.rb

Constant Summary collapse

API_HOST =
'http://api.map.baidu.com'
GEOCODER_PATH =
'/geocoder/v2/'

Instance Method Summary collapse

Instance Method Details

#calculate_ak_sn(queries, sk) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/baidu_api/geocoding/v2/geocoder.rb', line 26

def calculate_ak_sn(queries, sk)
  query_str = ERB::Util.url_encode("#{GEOCODER_PATH}?#{to_query(queries)}#{sk}")
  debug('unencrypted query', query_str)
  sn = Digest::MD5.hexdigest(query_str)
  debug('sn', sn)
  sn
end

#debug(subject, msg) ⇒ Object



48
49
50
# File 'lib/baidu_api/geocoding/v2/geocoder.rb', line 48

def debug(subject, msg)
  puts "#{subject}: #{msg}" if BaiduApi::Geocoding.config.debug
end

#fetch_query_params(data) ⇒ Object



42
43
44
45
46
# File 'lib/baidu_api/geocoding/v2/geocoder.rb', line 42

def fetch_query_params(data)
  %w(output ak address city coordtype location pois).map do |k|
    [k.intern, data[k.intern]]
  end.compact
end

#geocode(data) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/baidu_api/geocoding/v2/geocoder.rb', line 16

def geocode(data)
  queries = fetch_query_params(data) + [[:output, 'json']]
  url = "#{API_HOST}#{GEOCODER_PATH}?#{to_query(queries)}"
  url << "&sn=#{calculate_ak_sn(queries, data[:sk])}" if data[:sk]
  debug('url', url)
  open(url) do |http|
    ret = JSON.parse(http.read)
  end
end

#to_query(arr) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/baidu_api/geocoding/v2/geocoder.rb', line 34

def to_query(arr)
  query_str = arr.map do |k, v|
    v && "#{CGI.escape(k.to_s)}=#{CGI.escape(v)}"
  end.compact.join('&')
  debug('query_str', query_str)
  query_str
end