google-maps 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9e699e56ed738cfac0031a4f8feedb206f81d525
4
+ data.tar.gz: a875dc4fc48fbd7a96cf4a32c11ba4e0ee9f325d
5
+ SHA512:
6
+ metadata.gz: 73244c390ea76dbe02e4c38cc34634133b4e945d073e992f94ba163d252fe6ec59f496acaaca7c714bd42073068f90eece6513aca4fa7a3488b53440b92f1a2e
7
+ data.tar.gz: eea17d91911da12e944fabc9d5bf10e4c7ec0370cc74e460aea5e2dc0028953ec07df5283d8667722002c0083fc6bf21478a10cb989e5f8b226bc77a1a186f8f
@@ -0,0 +1,7 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
5
+ coverage/
6
+ .rvmrc
7
+ .DS_Store
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in google-maps.gemspec
4
+ gemspec
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2011 Zilverline / Daniël van Hoesel
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Google Maps
2
+ ====================
3
+
4
+ Installation
5
+ ------------
6
+ gem install google-maps
7
+
8
+ Usage Examples
9
+ --------------
10
+ Google::Maps.distance("Science Park, Amsterdam", "Deventer")
11
+ #=> "104 km"
12
+ Google::Maps.duration("Science Park, Amsterdam", "Deventer")
13
+ #=> "1 hour 12 mins"
14
+
15
+ route = Google::Maps.route("Science Park, Amsterdam", "Deventer")
16
+ route.distance.text
17
+ #=> "104 km"
18
+ route.duration.text
19
+ #=> "1 hour 12 mins"
20
+ route.distance.value
21
+ #=> 103712
22
+ route.duration.value
23
+ #=> 4337
24
+
25
+ Testing
26
+ -------
27
+ Run all tests:
28
+
29
+ rspec spec/
30
+
31
+ Copyright
32
+ ---------
33
+ Copyright (c) 2011 Zilverline / Daniël van Hoesel.
34
+ See [LICENSE](https://github.com/zilverline/google-maps/blob/master/LICENSE.mkd) for details.
@@ -0,0 +1,19 @@
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ require 'rspec/core/rake_task'
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ task :default => :spec
8
+
9
+ namespace :doc do
10
+ require 'yard'
11
+ YARD::Rake::YardocTask.new do |task|
12
+ task.files = ['HISTORY.mkd', 'LICENSE.mkd', 'lib/**/*.rb']
13
+ task.options = [
14
+ '--protected',
15
+ '--output-dir', 'doc/yard',
16
+ '--markup', 'markdown',
17
+ ]
18
+ end
19
+ end
@@ -0,0 +1,31 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "google-maps/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "google-maps"
7
+ s.version = Google::Maps::VERSION
8
+ s.authors = ["Daniel van Hoesel"]
9
+ s.email = ["daniel@danielvanhoesel.nl"]
10
+ s.homepage = "http://zilverline.com/"
11
+ s.summary = %q{Ruby wrapper for the Google Maps API}
12
+ s.description = %q{This is a ruby wrapper for the Google Maps api}
13
+
14
+ s.rubyforge_project = "google-maps"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ s.add_development_dependency('bundler', '~> 1.0')
22
+ s.add_development_dependency('rake', '~> 0.9')
23
+ s.add_development_dependency('rspec', '~> 2.6')
24
+ s.add_development_dependency('mocha', '~> 0.10')
25
+ s.add_development_dependency('simplecov', '~> 0.5')
26
+ s.add_development_dependency('yard', '~> 0.7')
27
+ s.add_dependency('json', '~> 1.7.5')
28
+ s.add_dependency('hashie', '~> 2.0.5')
29
+ s.add_dependency('httpclient', '~> 2.3.0.1')
30
+ s.add_dependency('ruby-hmac', '~> 0.4.0')
31
+ end
@@ -0,0 +1,38 @@
1
+ require File.expand_path('../google-maps/configuration', __FILE__)
2
+ require File.expand_path('../google-maps/logger', __FILE__)
3
+ require File.expand_path('../google-maps/route', __FILE__)
4
+ require File.expand_path('../google-maps/place', __FILE__)
5
+ require File.expand_path('../google-maps/location', __FILE__)
6
+
7
+ module Google
8
+ module Maps
9
+ extend Configuration
10
+ extend Logger
11
+
12
+ def self.route(from, to, language = self.default_language)
13
+ Route.new(from, to, language)
14
+ end
15
+
16
+ def self.distance(from, to, language = self.default_language)
17
+ Route.new(from, to, language).distance.text
18
+ end
19
+
20
+ def self.duration(from, to, language = self.default_language)
21
+ Route.new(from, to, language).duration.text
22
+ end
23
+
24
+ def self.places(keyword, language = self.default_language)
25
+ Place.find(keyword, language)
26
+ end
27
+
28
+ def self.place(reference, language = self.default_language)
29
+ PlaceDetails.find(reference, language)
30
+ end
31
+
32
+ def self.geocode(address, language = self.default_language)
33
+ Location.find(address, language)
34
+ rescue ZeroResultsException
35
+ []
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,89 @@
1
+ # require 'net/http'
2
+ require 'httpclient'
3
+ require 'uri'
4
+ require 'json'
5
+ require 'hashie/mash'
6
+ require 'base64'
7
+ require 'hmac'
8
+ require 'hmac-sha1'
9
+
10
+ module Google
11
+ module Maps
12
+
13
+ class InvalidResponseException < StandardError; end
14
+ class InvalidPremierConfigurationException < StandardError; end
15
+ class ZeroResultsException < InvalidResponseException; end
16
+
17
+ class API
18
+
19
+ STATUS_OK = "OK".freeze
20
+ STATUS_ZERO_RESULTS = "ZERO_RESULTS".freeze
21
+
22
+ class << self
23
+ def query(service, args = {})
24
+ default_args = {sensor: false, use_premier_signing: !Google::Maps.premier_client_id.nil?}
25
+ args = default_args.merge(args)
26
+ args = args.merge(Google::Maps.default_params[service]) if Google::Maps.default_params[service]
27
+ use_premier_signing = args.delete :use_premier_signing
28
+ args[:client] = Google::Maps.premier_client_id if use_premier_signing
29
+
30
+ url = url(service, args)
31
+ url = premier_signing(url) if use_premier_signing
32
+ result = Hashie::Mash.new response(url)
33
+ raise ZeroResultsException.new("Google did not return any results: #{result.status}") if result.status == STATUS_ZERO_RESULTS
34
+ raise InvalidResponseException.new("Google returned an error status: #{result.status}") if result.status != STATUS_OK
35
+ result
36
+ end
37
+
38
+ private
39
+
40
+ def decode_url_safe_base_64(value)
41
+ Base64.decode64(value.tr('-_','+/'))
42
+ end
43
+
44
+ def encode_url_safe_base_64(value)
45
+ Base64.encode64(value).tr('+/','-_')
46
+ end
47
+
48
+ def premier_signing(url)
49
+ raise InvalidPremierConfigurationException.new("No private key set, set Google::Maps.premier_key") if Google::Maps.premier_key.nil?
50
+
51
+ parsed_url = url.is_a?(URI) ? url : URI.parse(url)
52
+ url_to_sign = parsed_url.path + '?' + parsed_url.query
53
+
54
+ # Decode the private key
55
+ raw_key = decode_url_safe_base_64(Google::Maps.premier_key)
56
+
57
+ # create a signature using the private key and the URL
58
+ sha1 = HMAC::SHA1.new(raw_key)
59
+ sha1 << url_to_sign
60
+ raw_sig = sha1.digest
61
+
62
+ # encode the signature into base64 for url use form.
63
+ signature = encode_url_safe_base_64(raw_sig)
64
+
65
+ # prepend the server and append the signature.
66
+ "#{parsed_url.scheme}://#{parsed_url.host}#{url_to_sign}&signature=#{signature}".strip
67
+ end
68
+
69
+ def response(url)
70
+ JSON.parse(HTTPClient.new.get_content(url))
71
+ rescue Exception => error
72
+ Google::Maps.logger.error "#{error.message}"
73
+ raise InvalidResponseException.new("unknown error: #{error.message}")
74
+ end
75
+
76
+ def url(service, args = {})
77
+ url = URI.parse("#{Google::Maps.end_point}#{Google::Maps.send(service)}/#{Google::Maps.format}#{query_string(args)}")
78
+ Google::Maps.logger.debug("url before possible signing: #{url}")
79
+ url.to_s
80
+ end
81
+
82
+ def query_string(args = {})
83
+ '?' + args.map { |k,v| "%s=%s" % [URI.encode(k.to_s), URI.encode(v.to_s)] }.join('&') unless args.size <= 0
84
+ end
85
+ end
86
+ end
87
+
88
+ end
89
+ end
@@ -0,0 +1,70 @@
1
+ module Google
2
+ module Maps
3
+ # Defines constants and methods related to configuration
4
+ module Configuration
5
+ # An array of valid keys in the options hash when configuring an {Google::Maps::API}
6
+ VALID_OPTIONS_KEYS = [:end_point, :premier_key, :premier_client_id, :format, :directions_service, :places_service, :geocode_service, :api_key, :default_language, :place_details_service, :default_params].freeze
7
+
8
+ # By default, set "https://maps.googleapis.com/maps/api/" as the server
9
+ DEFAULT_END_POINT = "https://maps.googleapis.com/maps/api/".freeze
10
+
11
+ DEFAULT_DIRECTIONS_SERVICE = "directions".freeze
12
+ DEFAULT_PLACES_SERVICE = "place/autocomplete".freeze
13
+ DEFAULT_PLACE_DETAILS_SERVICE = "place/details".freeze
14
+ DEFAULT_GEOCODE_SERVICE = "geocode".freeze
15
+
16
+ DEFAULT_FORMAT = "json".freeze
17
+
18
+ # premier API key to sign parameters
19
+ DEFAULT_PREMIER_KEY = nil
20
+
21
+ # premier client id
22
+ DEFAULT_PREMIER_CLIENT_ID = nil
23
+
24
+ # a api key
25
+ DEFAULT_API_KEY = nil
26
+
27
+ # default language
28
+ DEFAULT_LANGUAGE = :en
29
+
30
+ # params to send which each request configured per service, ie.: {places_service: {location: "52.0910,5.1220", radius: 300000}}
31
+ DEFAULT_PARAMS = {}
32
+
33
+ # @private
34
+ attr_accessor *VALID_OPTIONS_KEYS
35
+
36
+ # When this module is extended, set all configuration options to their default values
37
+ def self.extended(base)
38
+ base.reset
39
+ end
40
+
41
+ # Convenience method to allow configuration options to be set in a block
42
+ def configure
43
+ yield self
44
+ end
45
+
46
+ # Create a hash of options and their values
47
+ def options
48
+ VALID_OPTIONS_KEYS.inject({}) do |option, key|
49
+ option.merge!(key => send(key))
50
+ end
51
+ end
52
+
53
+ # Reset all configuration options to defaults
54
+ def reset
55
+ self.end_point = DEFAULT_END_POINT
56
+ self.format = DEFAULT_FORMAT
57
+ self.directions_service = DEFAULT_DIRECTIONS_SERVICE
58
+ self.places_service = DEFAULT_PLACES_SERVICE
59
+ self.place_details_service = DEFAULT_PLACE_DETAILS_SERVICE
60
+ self.geocode_service = DEFAULT_GEOCODE_SERVICE
61
+ self.premier_client_id = DEFAULT_PREMIER_CLIENT_ID
62
+ self.premier_key = DEFAULT_PREMIER_KEY
63
+ self.api_key = DEFAULT_API_KEY
64
+ self.default_language = DEFAULT_LANGUAGE
65
+ self.default_params = DEFAULT_PARAMS
66
+ self
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,25 @@
1
+ require File.expand_path('../api', __FILE__)
2
+
3
+ module Google
4
+ module Maps
5
+ class Location
6
+ attr_reader :address, :latitude, :longitude
7
+ alias :to_s :address
8
+
9
+ def initialize(address, latitude, longitude)
10
+ @address = address
11
+ @latitude = latitude
12
+ @longitude = longitude
13
+ end
14
+
15
+ def lat_lng
16
+ [latitude, longitude]
17
+ end
18
+
19
+ def self.find(address, language=:en)
20
+ API.query(:geocode_service, :language => language, :address => address).results.map { |result| Location.new(result.formatted_address, result.geometry.location.lat, result.geometry.location.lng) }
21
+ end
22
+ end
23
+
24
+ end
25
+ end
@@ -0,0 +1,18 @@
1
+ require 'logger'
2
+
3
+ module Google
4
+ module Maps
5
+ module Logger
6
+
7
+ attr_accessor :logger
8
+
9
+ def log_file=(file)
10
+ self.logger = ::Logger.new(file)
11
+ end
12
+
13
+ def self.extended(base)
14
+ base.log_file = RUBY_PLATFORM.index(/mswin(?!ce)|mingw|cygwin|bccwin/) ? "nul" : "/dev/null"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,88 @@
1
+ require File.expand_path('../api', __FILE__)
2
+
3
+ module Google
4
+ module Maps
5
+
6
+ class Place
7
+ attr_reader :text, :html, :keyword, :reference
8
+ alias :to_s :text
9
+ alias :to_html :html
10
+
11
+ def initialize(data, keyword)
12
+ @text = data.description
13
+ @reference = data.reference
14
+ @html = highligh_keywords(data, keyword)
15
+ end
16
+
17
+ def self.find(keyword, language=:en)
18
+ args = {:language => language, :input => keyword }
19
+ args.merge!(key: Google::Maps.api_key) unless Google::Maps.api_key.nil?
20
+
21
+ API.query(:places_service, args).predictions.map{|prediction| Place.new(prediction, keyword) }
22
+ end
23
+
24
+ private
25
+
26
+ def highligh_keywords(data, keyword)
27
+ keyword = Regexp.escape(keyword)
28
+ matches = Array(keyword.scan(/\w+/))
29
+ html = data.description.dup
30
+ matches.each do |match|
31
+ html.gsub!(/(#{match})/i, '<strong>\1</strong>')
32
+ end
33
+
34
+ html
35
+ end
36
+ end
37
+
38
+ class PlaceDetails
39
+ attr_reader :data
40
+
41
+ def initialize(data)
42
+ @data = data
43
+ end
44
+
45
+ def latitude
46
+ @data.geometry.location.lat.to_s
47
+ end
48
+
49
+ def longitude
50
+ @data.geometry.location.lng.to_s
51
+ end
52
+
53
+ def reference
54
+ @data.reference
55
+ end
56
+
57
+ def address
58
+ @data.formatted_address
59
+ end
60
+ alias :to_s :address
61
+
62
+ def address_components
63
+ AddressComponentsProxy.new(@data.address_components)
64
+ end
65
+
66
+ def self.find(reference, language=:en)
67
+ args = {:language => language, :reference => reference}
68
+ args.merge!(key: Google::Maps.api_key) unless Google::Maps.api_key.nil?
69
+
70
+ PlaceDetails.new(API.query(:place_details_service, args).result)
71
+ end
72
+
73
+ class AddressComponentsProxy
74
+ def initialize(address_components)
75
+ @address_components = address_components
76
+ end
77
+
78
+ def method_missing(method, *args, &block)
79
+ raise ArgumentError unless args.empty?
80
+
81
+ @address_components.find do |component|
82
+ component.types.first == method.to_s
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
88
+ end