简体   繁体   English

使用 geocoder gem for rails,我如何获得访问者的城市?

[英]Using the geocoder gem for rails, how do i get the visitor's city?

https://github.com/alexreisner/geocoder https://github.com/alexreisner/geocoder

I can't find documentation to show the visitor's city from ip address?我找不到显示来自 ip 地址的访客所在城市的文件? I know how to with HTML5, but I would like to use the value geocoder has.我知道如何使用 HTML5,但我想使用地理编码器的值。 Thanks谢谢

It took a couple of hours for me to realize that the answer is pretty simple:我花了几个小时才意识到答案很简单:

request.location.city

Geocoder page has this example but I thought that I would need to declare request but no, nothing more is needed. Geocoder 页面有这个示例,但我认为我需要声明请求,但不需要,不需要更多。

If you don't have Geocoder you have to install the gem but nothing besides that.如果您没有 Geocoder,则必须安装 gem,除此之外别无他法。

How I did it was -我是怎么做到的——

location = Geokit::Geocoders::IpGeocoder.geocode(source_ip)
city = location.city
country = location.country

Here, source_ip is a string object.这里,source_ip 是一个字符串 object。

# app/models/user.rb
geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

Snippet from geocoder site .来自地理编码器网站的片段。

You could do it in 2 different ways你可以用两种不同的方式来做

1) If you could get visitors city/ address as a string then geocoder will automatically convert that in to latitude and longitude 1) 如果您可以将访问者城市/地址作为字符串,那么地理编码器会自动将其转换为纬度和经度

class Message < ActiveRecord::Base
  geocoded_by :full_address
  after_validation :geocode

  def full_address
    "#{city}, Sri Lanka"
  end

end

2) Or else you will have to track the ip of the visitor, example is in the home page on the 'geocoder' gem 2) 否则你将不得不跟踪访问者的 ip,例如在主页上的 'geocoder' gem

NOTE: And you could use near by method as follows注意:你可以使用 near by 方法如下

<Active Record Object List>.near(<City Name>, <distance>, :order => :distance)

Ex: @messages = @messages.near("colombo", 10, :order => :distance)

and there is a super-duper screen cast by ryan in railscasts并且在railscasts中有一个由 ryan 投射的超级屏幕

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM