Class: Graticule::Cli

Inherits:
Object
  • Object
show all
Defined in:
lib/graticule/cli.rb

Overview

A command line interface for geocoding. From the command line, run:

geocode 49423

Outputs:

# Holland, MI 49423 US
# latitude: 42.7654, longitude: -86.1085

Usage: geocode [options] location

Options:

-s, --service service            Geocoding service
-a, --apikey apikey              API key for the selected service
-h, --help                       Help

Class Method Summary collapse

Class Method Details

.start(args) ⇒ Object



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
# File 'lib/graticule/cli.rb', line 23

def self.start(args)
  options = { :service => :yahoo, :api_key => 'YahooDemo' }
  
  OptionParser.new do |opts|
    opts.banner = "Usage: geocode [options] location"
    opts.separator ""
    opts.separator "Options: "

    opts.on("-s service", %w(yahoo google geocoder_us metacarta), "--service service", "Geocoding service") do |service|
      options[:service] = service
    end
    
    opts.on("-a apikey", "--apikey apikey", "API key for the selected service")
    
    opts.on_tail("-h", "--help", "Help") do
      puts opts
      exit
    end
  end.parse! args

  options[:location] = args.join(" ")
  
  result = Graticule.service(options[:service]).new(options[:api_key]).locate(options[:location])
  location = (result.is_a?(Array) ? result.first : result)
  if location
    puts location.to_s(:coordinates => true)
  else
    puts "Location not found"
  end
rescue Graticule::CredentialsError
  $stderr.puts "Invalid API key. Pass your #{options[:service]} API key using the -a option. "
rescue OptionParser::InvalidArgument, OptionParser::InvalidOption,
    Graticule::Error => error
  $stderr.puts error.message
end