2015-11-02 36 views
0

我想要顯示以用戶位置爲中心的google地圖。我願意使用gmaps4railsgeokit-rails寶石,因爲我猜這些是最好的寶石。RoR:如何使用geokit-rails獲取lat和lng

我有什麼迄今已是地圖初始化:

<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寶石的位置,但它失敗:

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,但它不工作。

You can obtain the location for an IP at any time using the geocoder as in the following example:

location = IpGeocoder.geocode('12.215.42.19')

where Location is a GeoLoc instance containing the latitude, longitude, city, state, and country code. Also, the success value is true.

我收到以下錯誤:uninitialized constant WineryController::IpGeocoder。任何人都可以向我解釋這是什麼意思,以及如何繼續?我懷疑這可能是非常愚蠢的,但我仍然是一個新手。

+1

嘗試'@location = :: IpGeocoder.geocode( '181.169.135.95')' –

+0

@BradWerth我試過了,我得到了'未初始化的常量IpGeocoder' –

+0

這聽起來像你缺少一個需求 –

回答

0

嘗試這樣:

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

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地址這裏的關鍵教訓是Ruby會話是一種散列數據類型。因此,必須通過調用散列鍵(例如@location['lat']@location['lng'])來檢索散列值。

更多信息:Ruby - getting value of hash

相關問題