pablito.aven
pablito.aven

Reputation: 1165

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

I want to display a google maps centered at the user's location. I am willing to use gmaps4rails and geokit-rails gems, because I guess those are the best ones.

What I have so far is the map initialization:

<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>

which works fine. Now the problem is to get the latitude and longitud based on user IP. This is what I am trying, but I am getting no result. In the controller I try to get the location using geokit gem, but it fails:

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

I got this from geokit github, but it is not working.

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.

I am getting the following error: uninitialized constant WineryController::IpGeocoder. Can anyone explain me what does this mean, and how to go ahead? I suspect this might be something really stupid, but I am still a novice in rails.

Upvotes: 0

Views: 1279

Answers (1)

John Marbach
John Marbach

Reputation: 143

Try something like this:

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

Then in your view you can display the IP address by accessing the values of the hash:

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

The key lesson here is that a Ruby session is a hash data-type. Consequently, the values of the hash must be retrieved by calling the hash key, such as @location['lat'] and @location['lng'].

More info: Ruby - getting value of hash

Upvotes: 0

Related Questions