Sha256: a4aa363a5f93dc0f79d08aa680a4afa49f46bc763681a7995e27eabad0bc79fb

Contents?: true

Size: 995 Bytes

Versions: 2

Compression:

Stored size: 995 Bytes

Contents

require 'timezone/lookup/basic'
require 'timezone/error'
require 'json'
require 'uri'

module Timezone
  module Lookup
    class Google < ::Timezone::Lookup::Basic
      def initialize(config)
        if config.google_api_key.nil?
          raise(::Timezone::Error::InvalidConfig, 'missing api key')
        end
        super
      end

      def lookup(lat,lng)
        response = client.get(url(lat,lng))

        return unless response.code =~ /^2\d\d$/
        data = JSON.parse(response.body)

        if data['status'] != 'OK'
          raise(Timezone::Error::Google, data['errorMessage'])
        end

        data['timeZoneId']
      rescue => e
        raise(Timezone::Error::Google, e.message)
      end

      private

      def url(lat,lng)
          query = URI.encode_www_form(
            'location' => "#{lat},#{lng}",
            'timestamp' => Time.now.to_i,
            'key' => config.google_api_key)

          "/maps/api/timezone/json?#{query}"
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
timezone-0.3.11 lib/timezone/lookup/google.rb
timezone-0.3.10 lib/timezone/lookup/google.rb