Search code examples
ruby-on-railsgoogle-mapsruby-on-rails-4rails-geocoder

Geocoder: if response is over query limit


How can I ask a Geocoder gem address if the API query limit has been reached?

csv.each_with_index do |row, i|
  if !row[:location_1].nil?
    coords = row[:location_1]
    g = Geocoder.address(coords)
    row[:address] = g
  end

  if g.include?('over query limit')
    p "limit hit"
  end
end

I'm not sure which object to ask. The error comes through in the console:

Google Geocoding API error: over query limit.

But I'm not sure how to check for that in code. Any help?


Solution

  • You probably want to wrap your Geocoder.address in a begin/rescue block:

    csv.each_with_index do |row, i|
      if !row[:location_1].nil?
        coords = row[:location_1]
        begin
          g = Geocoder.address(coords)
          row[:address] = g
        rescue Geocoder::OverQueryLimitError
          p "limit hit"
        end
      end
    end
    

    Just a note, you'll probably want to break out of the loop in the rescue clause once you hit this so you don't spam the geocoding web service with bad requests.

    See Geocoder errors.