【问题标题】:RoR: How to get lat and lng using geokit-railsRoR:如何使用 geokit-rails 获取 lat 和 lng
【发布时间】:2015-11-02 23:24:45
【问题描述】:

我想显示以用户位置为中心的谷歌地图。我愿意使用gmaps4railsgeokit-rails gems,因为我猜它们是最好的。

到目前为止我所拥有的是地图初始化:

<div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>

<script>
$(document).ready(function(){
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
    markers = handler.addMarkers([
      {
        "lat": 0,
        "lng": 0,
        "picture": {
          "url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
          "width":  36,
          "height": 36
        },
        "infowindow": "hello!"
      }
    ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
  });
});
</script>

效果很好。现在的问题是根据用户IP获取纬度和经度。这是我正在尝试的,但我没有得到任何结果。在控制器中,我尝试使用 geokit gem 获取位置,但失败了:

def view
  @location = IpGeocoder.geocode('181.169.135.95') #I know here I should use `request.remote_ip`, but as I am on localhost I can't
end

我从geokit github 得到这个,但它不起作用。

您可以随时使用地理编码器获取 IP 的位置 如下例:

location = IpGeocoder.geocode('12.215.42.19')

其中 Location 是包含纬度、经度、城市、州和国家/地区代码的 GeoLoc 实例。另外,success 值为 true。

我收到以下错误:uninitialized constant WineryController::IpGeocoder。谁能解释我这是什么意思,以及如何继续?我怀疑这可能真的很愚蠢,但我仍然是 Rails 的新手。

【问题讨论】:

  • 试试@location = ::IpGeocoder.geocode('181.169.135.95')
  • @BradWerth 我试过了,我得到了uninitialized constant IpGeocoder
  • 听起来你缺少一个要求
  • @BradWerth 谢谢!另一个帖子帮助了我。现在我有另一个问题,在我看来,我调用@location.lat@location.lng,它只返回一个空字符串。有什么想法吗?

标签: ruby-on-rails ruby google-maps gmaps4rails geokit


【解决方案1】:

试试这样的:

application_controller.rb

class ApplicationController < ActionController::Base
  # Auto-geocode the user's ip address and store in the session.
  geocode_ip_address
  def geokit
    @location = session[:geo_location]  # @location is a GeoLoc instance.
  end
end

然后在您的视图中,您可以通过访问哈希值来显示 IP 地址:

<%= [@location['lat'],@location['lng']] %>

这里的关键教训是 Ruby 会话是一种哈希数据类型。因此,必须通过调用散列键来检索散列值,例如@location['lat']@location['lng']

更多信息:Ruby - getting value of hash

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2016-07-18
    相关资源
    最近更新 更多