簡體   English   中英

RoR:如何使用geokit-rails獲取經緯度

[英]RoR: How to get lat and lng using geokit-rails

我想顯示一個以用戶所在位置為中心的Google地圖。 我願意使用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的位置,如以下示例所示:

位置= IpGeocoder.geocode('12 .215.42.19')

其中Location是一個GeoLoc實例,其中包含緯度,經度,城市,州和國家/地區代碼。 同樣,成功值是真實的。

我收到以下錯誤: uninitialized constant WineryController::IpGeocoder 誰能解釋我的意思,以及如何繼續? 我懷疑這可能確實很愚蠢,但是我仍然是菜鳥的新手。

嘗試這樣的事情:

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-獲取哈希值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM