Tag Archives: geocode

Fetching Local Tweets in Ruby

Tests take forever because of all the HTTPRequests

Tests take forever because of all the HTTPRequests

As planned, I wrote a little class incorporating Geocoder and twitter_search so you can search for tweets within x miles (or kilometers) of an address.Geocoder does an excellent job of parsing addresses and twitter_search is simple and efficient.

Four thumbs up

Next phase I’d like to set up a little web interface showing tweets and tweeters. There’s something funny about hitting the internet to find out what’s going on around you.

Here’s the class, as you can see there are a few overridable defaults

require 'rubygems'
require 'geocoder'
require 'twitter_search'

class Twitter_Interface

  attr_accessor :tpp, :distance
  attr_reader   :address, :geocode
  attr          :geocoder, :client 

  def initialize addr = "", dist = "2mi", pp = 15
    @client   = TwitterSearch::Client.new
    @tpp      = pp
    @distance = dist
    @geocoder = initialize_geocoder
    set_location addr
  end

  # Could also use Yahoo API, but it requires API key.
  def initialize_geocoder geocoder = Geocoder::GeoCoderUs.new
    geocoder
  end

  def format_geocode geocode = @geocode
    if is_geocode? geocode
      return "#{geocode.latitude},#{geocode.longitude},#{@distance}"
    end
    ""
  end

  def tweets
    @client.query :geocode => format_geocode, :tpp => @tpp
  end

  def address_to_geocode addr = @address
    if addr == ""
      return ""
    end
    @geocoder.geocode addr
  end

  def is_geocode? geocode
    geocode.respond_to? "success?" and geocode.success?
  end

  def set_location addr
    @address = addr
    @geocode = address_to_geocode @address
  end

end

And here’s how you use it

t = Twitter_Interface.new "1600 pennsylvania ave nw washington dc"

#print the twitter query formatted geocode, default distance is 2 miles
puts t.format_geocode

#=>"38.898748,-77.037684,2mi"

#fetch the Twitter_Search::Tweets within 2 miles of the white house!
tweets = t.tweets

Download a .zip of the code / tests