Sha256: c05d5ddd3a97f072c0318be65582dc4ac1a8cb711627c8ebed9dde6012082724

Contents?: true

Size: 1.36 KB

Versions: 1

Compression:

Stored size: 1.36 KB

Contents

require "gogo_maps/version"
require 'faraday'
require 'json'

module GogoMaps
  class << self
    def get_latlng(address, opts={})
      GoogleMapClient.call(
        { address: address, language: :ja, sensor: false }.merge(opts),
        :to_latlng
      )
    end

    def get_address(lat, lng, opts={})
      GoogleMapClient.call(
        { latlng: "#{lat},#{lng}", language: :ja, sensor: false }.merge(opts),
        :to_address
      )
    end

    def random(opts={})
      lat,lng  = (0..1).map{ ((-180..180).to_a.sample + rand).round(8) }
      get_address(lat, lng, opts)
    rescue
      random #FIXIT:
    end
  end

  class GoogleMapClient
    ENDPOINT = 'http://maps.googleapis.com'
    @@_conn ||= Faraday.new(url: ENDPOINT) do |faraday|
      faraday.request  :url_encoded
      faraday.adapter  Faraday.default_adapter
    end

    def self.call(params, sym)
      response = @@_conn.get do |req|
        req.url '/maps/api/geocode/json'
        req.params = params
      end

      unless location = JSON.parse(response.body)['results'][0]
        fail 'Something wrong with Google API or your params'
      end

      case sym
        when :to_latlng
          location['geometry']['location'].each_with_object({}) do | (k, v), rslt |
            rslt[k.to_s.to_sym] = v
          end
        when :to_address
          location['formatted_address']
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gogo_maps-0.2.71826000 lib/gogo_maps.rb