Giter VIP home page Giter VIP logo

ruby-opencage-geocoder's Introduction

OpenCage Geocoder

A Ruby client for the OpenCage geocoding API.

Build status / Code quality / etc

Build Status Gem Version Mastodon Follow

Installation

gem install opencage-geocoder

Or in your Gemfile:

source 'https://rubygems.org'
gem 'opencage-geocoder'

Tutorial

You can find a comprehensive tutorial for using this module on the OpenCage site.

API Documentation

Complete documentation for the OpenCage geocoding API can be found at opencagedata.com/api.

Usage

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

Geocode an address or place name

results = geocoder.geocode('82 Clerkenwell Road, London')
p results.first.coordinates
# [ 51.5221558691, -0.100838524406 ]

results = geocoder.geocode('Manchester')
results.each { |res| p res.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 Japanese
results = geocoder.geocode('Manchester', countrycode: 'CA', language: 'ja')
p results.first.address
# "Manchester, ノバスコシア州, カナダ"
p results.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"
# }
p results.first.geometry # might be empty for some results
p results.first.bounds # might be empty for some results

Convert latitude, longitude to an address

result = geocoder.reverse_geocode(51.5019951, -0.0698806)
p result.address
# 'Bermondsey Wall West, Bermondsey, London Boro ...

Annotations

See the API documentation for a complete list of annotations.

result = geocoder.reverse_geocode(-22.6792, 14.5272)
p result.annotations['geohash']
# "k7fqfx6h5jbq5tn8tnpn"
p result.annotations['timezone']
# {"timezone"=>{"name"=>"Africa/Windhoek", "now_in_dst"=>0, "offset_sec"=>7200, "offset_string"=>200, "short_name"=>"CAT"}}

Error handling

The geocoder will return an OpenCage::Error subclass if there is a problem with either input or response, for example:

begin
  # Invalid API key
  geocoder =  OpenCage::Geocoder.new(api_key: 'invalid-api-key')
  geocoder.geocode('Manchester')
rescue OpenCage::Geocoder::AuthenticationError => e
  p 'invalid apikey'
rescue OpenCage::Geocoder::QuotaExceeded => e
  p 'over quota'
rescue StandardError => e
  p 'other error: ' + e.message
end

# Using strings instead of numbers for reverse geocoding
geocoder.reverse_geocode('51.5019951', '-0.0698806')
# raises OpenCage::Geocoder::InvalidRequest (not valid numeric coordinates: "51.5019951", "-0.0698806")

begin

Batch geocoding

Fill 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 file
  result = geocoder.reverse_geocode(Float(latitude), Float(longitude))
  results.push(result)
rescue ArgumentError, OpenCage::Geocoder::GeocodingError => error
  # Stop looping through the queries if there is an error
  puts "Error: #{error.message}"
  break
end

puts results.map(&:address)
# 韓國館, 金山十一街, 金山里, Hsinchu 30082, Taiwan
# David Hazan 11, NO Jerusalem, Israel
# هرجيسا, Jameeco Weyn, Hargeisa, Somalia
# Китайское бистро, Apraksin Yard, Михайловский проезд ...

Upgrading to version 3.0

  • Version 2.x raised OpenCage::Geocoder. Now OpenCage::Error is raised.

Upgrading to version 2.0

  • 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

Copyright (c) OpenCage GmbH. See LICENSE for details.

Who is OpenCage GmbH?

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.

ruby-opencage-geocoder's People

Contributors

dependabot[bot] avatar freyfogle avatar kaoru avatar mattcollins avatar mtmail avatar nickcharlton avatar olleolleolle avatar russointroitoa avatar sbscully avatar thestelz avatar xrx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ruby-opencage-geocoder's Issues

Old release (1.1.0)

The current version on rubygems is 1.1.0, if you follow the instructions on the README you won't be able to use it, unless you specify the github repository on the Gemfile.

The gem does not include all the gems that requires once being installed

Run into this issue while try to test the gem and the service in a couple of projects:

~/open-cage-test/vendor/ruby/2.1.0/gems/opencage-geocoder-0.1.0/lib/opencage/geocoder.rb:1:in `require_relative': cannot load such file -- ~/open-cage-test/vendor/ruby/2.1.0/gems/opencage-geocoder-0.1.0/lib/opencage/geocoder/location (LoadError)
from ~/open-cage-test/vendor/ruby/2.1.0/gems/opencage-geocoder-0.1.0/lib/opencage/geocoder.rb:1:in `<top (required)>'
from hi.rb:2:in `require'
from hi.rb:2:in `<main>'

I followed the usage instructions from the readme. I had gem 'opencage-geocoder' in the Gemfile && i require it like this require 'opencage/geocoder'

I also found out that if you tell bundle to install the gem with the :github, :path option the gem works correctly and you don't run into this problem.

[Feature Request] Alias lat & lng to latitude & longitude

I would like to request adding alias' to OpenCage::Geocoder::Location.lat and OpenCage::Geocoder::Location.lng to be OpenCage::Geocoder::Location.latitude and OpenCage::Geocoder::Location.longitude.

def lat
  @result['geometry']['lat'].to_f
end

+ alias latitude lat

def lng
  @result['geometry']['lng'].to_f
end

+ alias longitude lng

I can open a PR, but the guide said to open an issue first.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.