【问题标题】:How to store users' location?如何存储用户的位置?
【发布时间】:2012-08-16 23:32:12
【问题描述】:

我正在从事一个新项目,整天都在思考和寻找最佳方法,如何将用户的位置保存到数据库中。

我需要拯救他们的城市,国家。这里有点问题,因为例如对于欧洲人来说,这意味着 city=Berlincountry=Germany。 但对于美国用户来说,它就像 city=Los Angelescountry=California (state=USA)。

这就是我今天要面对的问题。

我在这个应用程序中的目标是根据他们的位置找到城市中的所有用户。还可以找到他们所在区域内的人,比如说 15 公里/英里。

我打算在RoR,PostgreSQL中实现该应用程序,该应用程序可能会在Heroku上运行。

解决这个“问题”的最佳方法是什么?你能给我一些建议、技巧吗?

谢谢

【问题讨论】:

  • 嗯,html5 geolocation + ajax or geocoder + ip lookup
  • 您应该存储 lat/lng + 城市详细信息
  • 你能给我举个例子吗?

标签: sql ruby-on-rails ruby geolocation location


【解决方案1】:

您可以使用 geokitgeokit-rails gem 来实现这一点。有关文档,请参见此处:https://github.com/imajes/geokit-rails

基本上,它的工作原理如下:您保存用户的地址数据,然后使用地理编码服务(例如 Google 地图或 Yahoo Placefinder)查找该地址并将其映射到空间中的某个点(纬度/经度)。然后可以使用这些点来计算距离等。

一个例子:

class User < ActiveRecord::Base
  # has the following db fields:
  # - city
  # - state
  # - country
  # - latitude
  # - longitude

  acts_as_mappable :default_units       => :miles, 
                   :default_formula     => :sphere, 
                   :lat_column_name     => :latitude,
                   :lng_column_name     => :longitude,
                   :auto_geocode        => {:field => :full_address}

  def full_address
    [city, state, country].reject(&:blank).join(', ')
  end
end

然后您可以执行以下操作:

# find all users in a city (this has nothing to do with geokit but is just a normal db lookup)
User.where(:city => 'New York')

# find all users that are within X miles of a place
User.find_within(300, 'Denver')

还有更多,请参阅文档...

此示例向您展示如何使用 geokit gem。这个宝石似乎不再处于积极开发中。所以也许值得一试geocoderhttps://github.com/alexreisner/geocoder

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 2013-05-18
    • 2021-07-18
    相关资源
    最近更新 更多