geo_location

通过用户的 IP 判断其所在 位置。
你可以选择 hostip.info (免费) 或 maxmind.com (收费),做为中间处理。

country.rb (两个方法)

 module GeoLocation

  class << self

    def country(country_code)
      return nil if GeoLocation::countries.empty?
      GeoLocation::countries[country_code.to_sym]
    end

    def build_countries
      if GeoLocation::countries.empty?
        data = {}

        file = File.join(File.dirname(__FILE__), 'countries.txt')
        File.open(file, "r") do |infile|
          while (line = infile.gets)
            countries = line.split("\n")
            countries.each do |c|
              c = c.split("  ")
              code = c[0].to_sym
              country = c[1]
              data[code] = country
            end # end countries.each
          end # end while
        end # end file.open

        GeoLocation::countries = data
      end # end if
    end

  end

end

timezone.rb (两个方法)

  module GeoLocation

  class << self

    def timezone(country, region=nil)
      return nil if GeoLocation::timezones.empty?
      (region.nil? || region.empty?) ? GeoLocation::timezones[country.to_sym] : GeoLocation::timezones[country.to_sym][region.to_sym]
    end

    def build_timezones
      if GeoLocation::timezones.empty?
        data = {}

        file = File.join(File.dirname(__FILE__), 'timezones.txt')
        File.open(file, "r") do |infile|
          while (line = infile.gets)
            zones = line.split("\n")
            zones.each do |z|
              zone = z.split("  ")
              country = zone[0].to_sym
              region = zone[1].empty? ? '' : zone[1].to_sym
              value = zone[2]

              data[country] = {} if data[country].nil?
              if region.to_s.empty?
                data[country] = value
              else
                data[country][region] = value
              end

            end # end zones.each
          end # end while
        end # end file.open

        GeoLocation::timezones = data
      end # end if
    end

  end

end

通过 find(ip=nil) 来查找

源代码 :

  def find(ip=nil)
      ip = GeoLocation::dev_ip unless GeoLocation::dev_ip.nil?
      return nil unless valid_ip(ip)
      return (GeoLocation::use == :maxmind) ? maxmind(ip) : hostip(ip)
    end

举例

location = GeoLocation.find('24.24.24.24') # => {:ip=>"24.24.24.24", :city=>"Liverpool", :region=>"NY", :country=>"United States", :country_code=>"US", :latitude=>"43.1059", :longitude=>"-76.2099", :timezone=>"America/New_York"}

puts location[:ip] # => 24.24.24.24
puts location[:city] # => Liverpool
puts location[:region] # => NY
puts location[:country] # => United States
puts location[:country_code] # => US
puts location[:latitude] # => 43.1059
puts location[:longitude] # => -76.2099
puts location[:timezone] # => America/New_York

你可能感兴趣的:(geo_location)