ruby-on-railsrails-geocoder

Rails geocoder gem find city


I am trying to find the city of the user, now I can see the address method working fine in my controller

def your_location
  Geocoder.address(request.remote_ip)
end

But I can't figure out how to find the user city.


Solution

  • From Geocoder GitHub:

    Geocoder adds location and safe_location methods to the standard Rack::Request object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:

    # returns Geocoder::Result object
    result = request.location
    

    location hash example:

    {
      "data"=>{
        "ip"=>"213.174.0.254",
        "city"=>"Lviv",
        "latitude"=>49.8383,
        "zip_code"=>"79000",
        "longitude"=>24.0232,
        "time_zone"=>"Europe/Kiev",
        "metro_code"=>0,
        "region_code"=>"46",
        "region_name"=>"L'vivs'ka Oblast'",
        "country_code"=>"UA",
        "country_name"=>"Ukraine"
      },
      "cache_hit"=>nil
    }