RAILS 获取网站地理位置和标题

时间

我有用户放置网站 url 的表单,需要获取其地理位置和标题,如下所示:https : //www.site24x7.com/find-website-location.html 我是 Rails 新手,不确定 Geokit 是否是方法来做到这一点。任何人都可以帮助如何开始处理它?

马克·梅里特

您可以使用普通的旧 Ruby 来处理大部分内容。您可以使用各种 gem 来处理它……但是依赖项越少越好!这是一个例子...

# put this in the lib directory and name it location.rb
module Location
  require 'socket'
  require 'net/http'
  require 'json'

  def get_ip_address(url)
    IPSocket::getaddress(url)
  end

  def get_location_info(url)
    ip_address = get_ip_address(url)
    location = Net::HTTP.get(URI("https://ipapi.co/#{ip_address}/json/"))
    JSON.parse(location)
  end

  module_function :get_ip_address
  module_function :get_location_info
end

从 get_location_info 方法返回的 JSON 将如下所示......

{"ip"=>"108.163.210.34", "city"=>"Chicago", "region"=>"Illinois",
 "region_code"=>"IL", "country"=>"US", "country_name"=>"United States", 
"continent_code"=>"NA", "in_eu"=>false, "postal"=>"60604", "latitude"=>41.8776,
 "longitude"=>-87.6272, "timezone"=>"America/Chicago", "utc_offset"=>"-0500",
 "country_calling_code"=>"+1", "currency"=>"USD", "languages"=>"en-US,es-US,haw,fr", "asn"=>"AS32475", "org"=>"SingleHop LLC"}

所以现在你可以require 'location'在你的控制器中使用这个方法来获取信息

# at the top of your controller require 'location' 
def show
  # use a form that passes in the url to this show action to make it availabe in the params
  location_info = Location.get_location_info(params[:url])
  @ip = location_info["ip"]
  @city = location_info["city"]
  # other info you want to display in the view from location_info
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章