如何自动检测用户的位置并保存在数据库中?

时间:2018-06-30 17:09:41

标签: ruby-on-rails ruby rubygems

我目前有一个Tracker应用程序,我想让Rails通过IP地址检测用户的位置(在我的应用程序中注册)

并保存LatitudeLongitude,就像iplocation site

用户模型包含idusernameemailpasswordLatitudeLatitude

3 个答案:

答案 0 :(得分:2)

您可以将用户的IP地址传递到将IP映射到位置的API。

执行此操作的一种方法是在lib中创建一个ruby模块,该模块具有一种方法,该方法接受IP地址并将请求发送到API以获取位置。

module Location
  require 'net/http'
  require 'json'

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

  module_function :get_location
end

返回的JSON包括经度和纬度。

然后您可以从“用户”控制器调用此方法

require 'location'

class UsersController < ApplicationController
  def create
    @user = User.new(params.require(:user).permit(:longitude, :latitude))
    location = get_user_location

    @user.longitude = location["longitude"]
    @user.latitude = location["latitude"]

    if @user.save
      # Do something
    else
      # Do somehting else
    end
  end

  private

  def get_user_location
    ip_address = request.remote_ip
    Location.get_location ip_address
  end
end 

注意:ip_address不能在本地工作,因此要测试它,您必须在ip地址中进行硬编码,而不是调用request.remote_ip(即ip_address =“ 8.8.8.8”)。

编辑: 更新用户位置将需要与在create操作期间进行设置基本相同的逻辑。因此,我建议仅将所有逻辑提取到模块中……类似

module Location
  require 'net/http'
  require 'json'

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

  def set_location user ip_address
    location = get_location ip_address
    user.longitude = location["longitude"]
    user.latitude = location["latitude"]
    user.save
  end

  module_function :set_location
end

这将使您摆脱用户控制器中的所有位置逻辑,然后在整个控制器中重用set_location方法。

答案 1 :(得分:1)

脚本形式anujay-jsfiddle(http://jsfiddle.net/anujay0402/TPhUC/

HTML

<h3>Client side IP geolocation using</h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>

脚本

$.get("http://ipinfo.io", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#address").html("Location: " + response.city + ", " + response.region + "," + response.country );
    $("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");

输出

Client side IP geolocation using
IP: 45.11.14.1
Location: Chennai, Tamil Nadu,IN
Full response:
{
    "ip": "45.11.14.1",
    "hostname": "45.11.14.1.live.vodafone.in",
    "city": "Chennai",
    "region": "Tamil Nadu",
    "country": "IN",
    "loc": "13.03,80.23",
    "postal": "009144",
    "org": "AS38266 Vodafone Essar Ltd., Telecommunication - Value Added Services,"
}

答案 2 :(得分:0)

如果您不想弄乱会话信息,实际上Devise gem允许您捕获IP地址。

查看Devise的可跟踪功能here