my little geocoder class for Ruby on Rails

17 December 2009 | 10:20 am by codeboxer

works like a charm.


class GetLatLong
require 'open-uri'

attr_reader :latitude
attr_reader :longitude
attr_reader :message
attr_reader :valid

attr_writer :address
attr_writer :state
attr_writer :city
attr_writer :zip

YAHOO_KEY = "redacted"

  def initialize
    @valid=true
  end

  def run
    load_info
  end
  
  def load_info 
    #add plus signs to street and city
    @address=@address.split(" ").collect {|add| "#{add}+"}
    @city=@city.split(" ").collect {|ci| "#{ci}+"}
    #wait a little because YAHOO hates too many subsequent calls TOO QUICKLY
    sleep 1
    xpath = "http://local.yahooapis.com/MapsService/V1/geocode?appid=#{YAHOO_KEY}&street=#{@address}&city=#{@city}&state=#{@state}&zip=#{@zip}"
    uri = URI.parse(xpath)
    
    begin
      uri.open { |f|
            puts "Fetched document: #{f.base_uri}"
            # Save the response body
            @response = f.read
            }
    
      search = XmlSimple.xml_in(@response)
      @latitude = search["Result"][0]["Latitude"][0]
      @longitude = search["Result"][0]["Longitude"][0]
      puts "Your results:\n"
    rescue  => ex
      puts "error\n#{ex.message} "
      @valid=false
    end
      "lat:#{@latitude} long:#{@longitude}"
  end

end

and is used like this:


ll = GetLatLong.new
ll.address=address_value
ll.city=city_value
ll.state=state_value
ll.zip=zip_value
puts ll.run
send_this[6]=ll.latitude
send_this[7]=ll.longitude

Nice and easy.

Recommend Me




My Site Links

Screenshots are featured above. If you visit gmgpulse, you may login as demo/demo.

Rockstar Television


© 2008-10 Krister Axel and codeboxer.com