首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >RAILS获取网站地理位置和标题

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

Stack Overflow用户
提问于 2018-07-07 05:28:47
回答 1查看 53关注 0票数 0

我有一个表单,用户把网站的网址,并需要获得它的地理位置和标题,就像这里:https://www.site24x7.com/find-website-location.html我是新手在Rails,不确定Geokit是一个这样做的方式。有谁能帮我解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-07 08:17:35

您可以使用普通的老式Ruby来处理大部分问题。您可以使用各种gem来处理it...but,依赖项越少越好!这里有一个例子..。

代码语言:javascript
复制
# 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将如下所示……

代码语言:javascript
复制
{"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'并使用此方法来获取信息

代码语言:javascript
复制
# 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51217833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档