2015-11-02 86 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

相关问题