A Ruby client for the OpenCage geocoding API.
gem install opencage-geocoder
Or in your Gemfile:
source'https://rubygems.org'gem'opencage-geocoder'You can find a comprehensive tutorial for using this module on the OpenCage site.
Complete documentation for the OpenCage geocoding API can be found at opencagedata.com/api.
There is an Agent Skill for working with the OpenCage Geocoding API which includes a reference file for developing in Ruby using this gem.
Create an instance of the geocoder, passing a valid OpenCage Geocoder API key:
require'opencage/geocoder'geocoder=OpenCage::Geocoder.new(api_key: 'your-api-key-here')results=geocoder.geocode('82 Clerkenwell Road, London')presults.first.coordinates# [ 51.5221558691, -0.100838524406 ]results=geocoder.geocode('Manchester')results.each{ |res| pres.address}# "Manchester, Greater Manchester, England, United Kingdom"# "Manchester, NH, United States of America"# "Manchester, Jamaica"# "Manchester, CT 06042, United States of America"# ...# We want the city in Canada and results in Japaneseresults=geocoder.geocode('Manchester',countrycode: 'CA',language: 'ja')presults.first.address# "Manchester, ノバスコシア州, カナダ"presults.first.components# {# "_type" => "city",# "city" => "Manchester",# "county" => "Guysborough County",# "state" => "ノバスコシア州",# "state_code" => "NS",# "country" => "カナダ",# "country_code" => "ca",# "ISO_3166-1_alpha-2" => "CA",# "ISO_3166-1_alpha-3" => "CAN"# }presults.first.geometry# might be empty for some resultspresults.first.bounds# might be empty for some resultsresult=geocoder.reverse_geocode(51.5019951, -0.0698806)presult.address# 'Bermondsey Wall West, Bermondsey, London Boro ...See the API documentation for a complete list of annotations.
result=geocoder.reverse_geocode(-22.6792,14.5272)presult.annotations['geohash']# "k7fqfx6h5jbq5tn8tnpn"presult.annotations['timezone']# {"timezone"=>{"name"=>"Africa/Windhoek", "now_in_dst"=>0, "offset_sec"=>7200, "offset_string"=>200, "short_name"=>"CAT"}}The geocoder will return an OpenCage::Error subclass if there is a
problem with either input or response, for example:
begin# Invalid API keygeocoder=OpenCage::Geocoder.new(api_key: 'invalid-api-key')geocoder.geocode('Manchester')rescueOpenCage::Error::AuthenticationError=>ep'invalid apikey'rescueOpenCage::Error::QuotaExceeded=>ep'over quota'rescueStandardError=>ep'other error: ' + e.messageend# Using strings instead of numbers for reverse geocodinggeocoder.reverse_geocode('51.5019951','-0.0698806')# raises OpenCage::Error::InvalidRequest (not valid numeric coordinates: "51.5019951", "-0.0698806")beginFill a text file queries.txt with queries:
24.77701,121.02189
31.79261,35.21785
9.54828,44.07715
59.92903,30.32989
Then loop through the file:
geocoder=OpenCage::Geocoder.new(api_key: 'your-api-key-here')results=[]File.foreach('queries.txt')do |line|
latitude,longitude=line.chomp.split(',')# Use Float() rather than #to_f because it will throw an ArgumentError if# there is an invalid line in the queries.txt fileresult=geocoder.reverse_geocode(Float(latitude),Float(longitude))results.push(result)rescueArgumentError,OpenCage::Error::GeocodingError=>error# Stop looping through the queries if there is an errorputs"Error: #{error.message}"breakendputsresults.map(&:address)# 韓國館, 金山十一街, 金山里, Hsinchu 30082, Taiwan# David Hazan 11, NO Jerusalem, Israel# هرجيسا, Jameeco Weyn, Hargeisa, Somalia# Китайское бистро, Apraksin Yard, Михайловский проезд ...- Version 2.x raised
OpenCage::Geocoder. NowOpenCage::Erroris raised.
- Version 0.1x only returned one result
geocoder.geocode('Berlin').coordinates # Version 0.12
geocoder.geocode('Berlin').first.coordinates # Version 2
geocoder.reverse_geocode(50, 7).name # Version 0.12
geocoder.reverse_geocode(50, 7).address # Version 2
- Version 0.1x raised an error when no result was found. Version 2 returns an empty list (forward) or nil (reverse).
Copyright (c) OpenCage GmbH. See LICENSE for details.
We run a worldwide geocoding API and geosearch service based on open data. Learn more about us.
We also run Geomob, a series of regular meetups for location based service creators, where we do our best to highlight geoinnovation. If you like geo stuff, you will probably enjoy the Geomob podcast.
