/ Published in: Ruby
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
require 'net/http' require 'uri' require "rexml/document" # Retrieves US Location data based on a passed in Zipcode. Uses # Google Maps geocoding service to retrieve a Hash of city, state, and zip # For more info on the service see: http://code.google.com/apis/maps/documentation/geocoding/ # # example: # puts get_location_data(97030).inspect # outputs: # {:state=>"OR", :zip=>"97030", :city=>"Gresham"} def get_location_data(zip) url = "http://maps.google.com/maps/geo" uri = URI.parse(url) req = Net::HTTP::Get.new(uri.path + "?output=xml&q=#{zip}") res = Net::HTTP.start(uri.host, uri.port) do |http| http.request(req) end data = res.body result = {} address = "" doc = REXML::Document.new data doc.elements.each('//Placemark[1]/address') do |element| address = element.text end if address parts = address.split(/[,\s*]/) result[:city] = parts[0] result[:state] = parts[2] result[:zip] = parts[3] end result end