我有一个表单,用户把网站的网址,并需要获得它的地理位置和标题,就像这里:https://www.site24x7.com/find-website-location.html我是新手在Rails,不确定Geokit是一个这样做的方式。有谁能帮我解决这个问题吗?
发布于 2018-07-07 08:17:35
您可以使用普通的老式Ruby来处理大部分问题。您可以使用各种gem来处理it...but,依赖项越少越好!这里有一个例子..。
# 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
https://stackoverflow.com/questions/51217833
复制相似问题