Skip to content

Instantly share code, notes, and snippets.

@mimay
Forked from ole/geocode_coordinates.rb
Created March 25, 2014 08:11
Show Gist options
  • Save mimay/9757131 to your computer and use it in GitHub Desktop.
Save mimay/9757131 to your computer and use it in GitHub Desktop.

Revisions

  1. @ole ole created this gist Jan 23, 2014.
    45 changes: 45 additions & 0 deletions geocode_coordinates.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    #!/usr/bin/env ruby

    # Determines the coordinates (latitude and longitude) of the places or
    # addresses passed as arguments (either on the command line or via stdin)
    # and prints the results.

    # This script requires the Ruby Geocoder gem by Alex Reisner
    # (http://www.rubygeocoder.com).
    # To install the gem, run this command from a Terminal session:
    #
    # sudo gem install geocoder
    #
    # If you are using a Ruby version manager such as rbenv or RVM, make sure
    # to install the Geocoder gem in the operating system's Ruby installation
    # if you use this script inside an OS X Automator action.
    # For example, in rbenv, call rbenv global system before installing.

    require 'geocoder'

    if ARGV.count > 0
    input = ARGV
    else
    input = ARGF
    input.set_encoding("utf-8") # required to handle non-ASCII characters in Automator action
    end
    output = ""

    input.each do |address|
    trimmed_address = address.strip

    if trimmed_address.empty?
    output += "\n"
    next
    end

    geocode_result = Geocoder.search(trimmed_address)
    if geocode_result.first
    coordinates = geocode_result.first.coordinates.join(", ")
    else
    coordinates = "Not found"
    end
    output += "#{coordinates}\n"
    end

    puts output