module Barometer # # A simple Geo class # # Used to store location data from Graticule or HTTParty and convert # into just the data needed for geocoding # class Geo attr_accessor :latitude, :longitude attr_accessor :locality, :region, :country, :country_code, :address # # this will take a Location object (either generated by Graticule # or HTTParty), and fill in the applicable data # def initialize(location=nil) return unless location has_graticule = false begin Graticule has_graticule = true rescue # do nothing, Graticule not available end if has_graticule raise ArgumentError unless (location.is_a?(Graticule::Location) || location.is_a?(Hash)) else raise ArgumentError unless location.is_a?(Hash) end if has_graticule && location.class == Graticule::Location self.build_from_graticule(location) elsif location.class == Hash self.build_from_httparty(location) end self end def build_from_graticule(location=nil) return nil unless location begin require 'rubygems' require 'graticule' $:.unshift(File.dirname(__FILE__)) # load some changes to Graticule # TODO: attempt to get changes into Graticule gem require 'extensions/graticule' end raise ArgumentError unless location.is_a?(Graticule::Location) @latitude = location.latitude @longitude = location.longitude @locality = location.locality @region = location.region @country = location.country @country_code = location.country_code @address = location.address_line end def build_from_httparty(location=nil) return nil unless location raise ArgumentError unless location.is_a?(Hash) placemark = location["Placemark"] placemark = placemark.first if placemark.is_a?(Array) if placemark && placemark["Point"] && placemark["Point"]["coordinates"] @latitude = placemark["Point"]["coordinates"].split(',')[1].to_f @longitude = placemark["Point"]["coordinates"].split(',')[0].to_f end if placemark && placemark["AddressDetails"] && placemark["AddressDetails"]["Country"] if placemark["AddressDetails"]["Country"]["AdministrativeArea"] if placemark["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"] locality = placemark["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"] else locality = placemark["AddressDetails"]["Country"]["AdministrativeArea"]["Locality"] end if locality @locality = locality["LocalityName"] end @region = placemark["AddressDetails"]["Country"]["AdministrativeArea"]["AdministrativeAreaName"] end @country = placemark["AddressDetails"]["Country"]["CountryName"] @country_code = placemark["AddressDetails"]["Country"]["CountryNameCode"] @address = placemark["AddressDetails"]["Country"]["AddressLine"] end end def coordinates [@latitude, @longitude].join(',') end end end