我有一个表单,用户可以在其中放置网站网址,并需要获取其地理位置和标题,例如:https://www.site24x7.com/find-website-location.html 我是Rails的新手,不确定是否可以通过Geokit做到这一点。任何人都可以帮助如何开始处理它?</ p>
答案 0 :(得分:0)
您可以使用普通的旧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