repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/config/config_generator.rb | lib/generators/geocoder/config/config_generator.rb | require 'rails/generators'
module Geocoder
class ConfigGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
desc "This generator creates an initializer file at config/initializers, " +
"with the default configuration options for Geocoder."
def add_initializer
template "initializer.rb", "config/initializers/geocoder.rb"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/config/templates/initializer.rb | lib/generators/geocoder/config/templates/initializer.rb | Geocoder.configure(
# Geocoding options
# timeout: 3, # geocoding service timeout (secs)
# lookup: :nominatim, # name of geocoding service (symbol)
# ip_lookup: :ipinfo_io, # name of IP address geocoding service (symbol)
# language: :en, # ISO-639 language code
# use_https: false, # use HTTPS for lookup requests? (if supported)
# http_proxy: nil, # HTTP proxy server (user:pass@host:port)
# https_proxy: nil, # HTTPS proxy server (user:pass@host:port)
# api_key: nil, # API key for geocoding service
# cache: nil, # cache object (must respond to #[], #[]=, and #del)
# Exceptions that should not be rescued by default
# (if you want to implement custom error handling);
# supports SocketError and Timeout::Error
# always_raise: [],
# Calculation options
# units: :mi, # :km for kilometers or :mi for miles
# distances: :linear # :spherical or :linear
# Cache configuration
# cache_options: {
# expiration: 2.days,
# prefix: 'geocoder:'
# }
)
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/sql.rb | lib/geocoder/sql.rb | module Geocoder
module Sql
extend self
##
# Distance calculation for use with a database that supports POWER(),
# SQRT(), PI(), and trigonometric functions SIN(), COS(), ASIN(),
# ATAN2().
#
# Based on the excellent tutorial at:
# http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
#
def full_distance(latitude, longitude, lat_attr, lon_attr, options = {})
units = options[:units] || Geocoder.config.units
earth = Geocoder::Calculations.earth_radius(units)
"#{earth} * 2 * ASIN(SQRT(" +
"POWER(SIN((#{latitude.to_f} - #{lat_attr}) * PI() / 180 / 2), 2) + " +
"COS(#{latitude.to_f} * PI() / 180) * COS(#{lat_attr} * PI() / 180) * " +
"POWER(SIN((#{longitude.to_f} - #{lon_attr}) * PI() / 180 / 2), 2)" +
"))"
end
##
# Distance calculation for use with a database without trigonometric
# functions, like SQLite. Approach is to find objects within a square
# rather than a circle, so results are very approximate (will include
# objects outside the given radius).
#
# Distance and bearing calculations are *extremely inaccurate*. To be
# clear: this only exists to provide interface consistency. Results
# are not intended for use in production!
#
def approx_distance(latitude, longitude, lat_attr, lon_attr, options = {})
units = options[:units] || Geocoder.config.units
dx = Geocoder::Calculations.longitude_degree_distance(30, units)
dy = Geocoder::Calculations.latitude_degree_distance(units)
# sin of 45 degrees = average x or y component of vector
factor = Math.sin(Math::PI / 4)
"(#{dy} * ABS(#{lat_attr} - #{latitude.to_f}) * #{factor}) + " +
"(#{dx} * ABS(#{lon_attr} - #{longitude.to_f}) * #{factor})"
end
def within_bounding_box(sw_lat, sw_lng, ne_lat, ne_lng, lat_attr, lon_attr)
spans = "#{lat_attr} BETWEEN #{sw_lat.to_f} AND #{ne_lat.to_f} AND "
# handle box that spans 180 longitude
if sw_lng.to_f > ne_lng.to_f
spans + "(#{lon_attr} BETWEEN #{sw_lng.to_f} AND 180 OR " +
"#{lon_attr} BETWEEN -180 AND #{ne_lng.to_f})"
else
spans + "#{lon_attr} BETWEEN #{sw_lng.to_f} AND #{ne_lng.to_f}"
end
end
##
# Fairly accurate bearing calculation. Takes a latitude, longitude,
# and an options hash which must include a :bearing value
# (:linear or :spherical).
#
# For use with a database that supports MOD() and trigonometric functions
# SIN(), COS(), ASIN(), ATAN2().
#
# Based on:
# http://www.beginningspatial.com/calculating_bearing_one_point_another
#
def full_bearing(latitude, longitude, lat_attr, lon_attr, options = {})
degrees_per_radian = Geocoder::Calculations::DEGREES_PER_RADIAN
case options[:bearing] || Geocoder.config.distances
when :linear
"MOD(CAST(" +
"(ATAN2( " +
"((#{lon_attr} - #{longitude.to_f}) / #{degrees_per_radian}), " +
"((#{lat_attr} - #{latitude.to_f}) / #{degrees_per_radian})" +
") * #{degrees_per_radian}) + 360 " +
"AS decimal), 360)"
when :spherical
"MOD(CAST(" +
"(ATAN2( " +
"SIN( (#{lon_attr} - #{longitude.to_f}) / #{degrees_per_radian} ) * " +
"COS( (#{lat_attr}) / #{degrees_per_radian} ), (" +
"COS( (#{latitude.to_f}) / #{degrees_per_radian} ) * SIN( (#{lat_attr}) / #{degrees_per_radian})" +
") - (" +
"SIN( (#{latitude.to_f}) / #{degrees_per_radian}) * COS((#{lat_attr}) / #{degrees_per_radian}) * " +
"COS( (#{lon_attr} - #{longitude.to_f}) / #{degrees_per_radian})" +
")" +
") * #{degrees_per_radian}) + 360 " +
"AS decimal), 360)"
end
end
##
# Totally lame bearing calculation. Basically useless except that it
# returns *something* in databases without trig functions.
#
def approx_bearing(latitude, longitude, lat_attr, lon_attr, options = {})
"CASE " +
"WHEN (#{lat_attr} >= #{latitude.to_f} AND " +
"#{lon_attr} >= #{longitude.to_f}) THEN 45.0 " +
"WHEN (#{lat_attr} < #{latitude.to_f} AND " +
"#{lon_attr} >= #{longitude.to_f}) THEN 135.0 " +
"WHEN (#{lat_attr} < #{latitude.to_f} AND " +
"#{lon_attr} < #{longitude.to_f}) THEN 225.0 " +
"WHEN (#{lat_attr} >= #{latitude.to_f} AND " +
"#{lon_attr} < #{longitude.to_f}) THEN 315.0 " +
"END"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/version.rb | lib/geocoder/version.rb | module Geocoder
VERSION = "1.8.6"
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/exceptions.rb | lib/geocoder/exceptions.rb | require 'timeout'
module Geocoder
class Error < StandardError
end
class ConfigurationError < Error
end
class OverQueryLimitError < Error
end
class ResponseParseError < Error
attr_reader :response
def initialize(response)
@response = response
end
end
class RequestDenied < Error
end
class InvalidRequest < Error
end
class InvalidApiKey < Error
end
class ServiceUnavailable < Error
end
class LookupTimeout < ::Timeout::Error
end
class NetworkError < Error
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/logger.rb | lib/geocoder/logger.rb | require 'logger'
module Geocoder
def self.log(level, message)
Logger.instance.log(level, message)
end
class Logger
include Singleton
SEVERITY = {
debug: ::Logger::DEBUG,
info: ::Logger::INFO,
warn: ::Logger::WARN,
error: ::Logger::ERROR,
fatal: ::Logger::FATAL
}
def log(level, message)
unless valid_level?(level)
raise StandardError, "Geocoder tried to log a message with an invalid log level."
end
if current_logger.respond_to? :add
current_logger.add(SEVERITY[level], message)
else
raise Geocoder::ConfigurationError, "Please specify valid logger for Geocoder. " +
"Logger specified must be :kernel or must respond to `add(level, message)`."
end
nil
end
private # ----------------------------------------------------------------
def current_logger
logger = Geocoder.config[:logger]
if logger == :kernel
logger = Geocoder::KernelLogger.instance
end
logger
end
def valid_level?(level)
SEVERITY.keys.include?(level)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/esri_token.rb | lib/geocoder/esri_token.rb | module Geocoder
class EsriToken
attr_accessor :value, :expires_at
def initialize(value, expires_at)
@value = value
@expires_at = expires_at
end
def to_s
@value
end
def active?
@expires_at > Time.now
end
def self.generate_token(client_id, client_secret, expires=1440)
# creates a new token that will expire in 1 day by default
getToken = Net::HTTP.post_form URI('https://www.arcgis.com/sharing/rest/oauth2/token'),
f: 'json',
client_id: client_id,
client_secret: client_secret,
grant_type: 'client_credentials',
expiration: expires # (minutes) max: 20160, default: 1 day
response = JSON.parse(getToken.body)
if response['error']
Geocoder.log(:warn, response['error'])
else
token_value = response['access_token']
expires_at = Time.now + (expires * 60)
new(token_value, expires_at)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/query.rb | lib/geocoder/query.rb | module Geocoder
class Query
attr_accessor :text, :options
def initialize(text, options = {})
self.text = text
self.options = options
end
def execute
lookup.search(text, options)
end
def to_s
text
end
def sanitized_text
if coordinates?
if text.is_a?(Array)
text.join(',')
else
text.split(/\s*,\s*/).join(',')
end
else
text.to_s.strip
end
end
##
# Get a Lookup object (which communicates with the remote geocoding API)
# appropriate to the Query text.
#
def lookup
if !options[:street_address] and (options[:ip_address] or ip_address?)
name = options[:ip_lookup] || Configuration.ip_lookup || Geocoder::Lookup.ip_services.first
else
name = options[:lookup] || Configuration.lookup || Geocoder::Lookup.street_services.first
end
Lookup.get(name)
end
def url
lookup.query_url(self)
end
##
# Is the Query blank? (ie, should we not bother searching?)
# A query is considered blank if its text is nil or empty string AND
# no URL parameters are specified.
#
def blank?
!params_given? and (
(text.is_a?(Array) and text.compact.size < 2) or
text.to_s.match(/\A\s*\z/)
)
end
##
# Does the Query text look like an IP address?
#
# Does not check for actual validity, just the appearance of four
# dot-delimited numbers.
#
def ip_address?
IpAddress.new(text).valid? rescue false
end
##
# Is the Query text a loopback or private IP address?
#
def internal_ip_address?
ip_address? && IpAddress.new(text).internal?
end
##
# Is the Query text a loopback IP address?
#
def loopback_ip_address?
ip_address? && IpAddress.new(text).loopback?
end
##
# Is the Query text a private IP address?
#
def private_ip_address?
ip_address? && IpAddress.new(text).private?
end
##
# Does the given string look like latitude/longitude coordinates?
#
def coordinates?
text.is_a?(Array) or (
text.is_a?(String) and
!!text.to_s.match(/\A-?[0-9\.]+, *-?[0-9\.]+\z/)
)
end
##
# Return the latitude/longitude coordinates specified in the query,
# or nil if none.
#
def coordinates
sanitized_text.split(',') if coordinates?
end
##
# Should reverse geocoding be performed for this query?
#
def reverse_geocode?
coordinates?
end
def language
options[:language]
end
private # ----------------------------------------------------------------
def params_given?
!!(options[:params].is_a?(Hash) and options[:params].keys.size > 0)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/railtie.rb | lib/geocoder/railtie.rb | require 'geocoder/models/active_record'
module Geocoder
if defined? Rails::Railtie
require 'rails'
class Railtie < Rails::Railtie
initializer 'geocoder.insert_into_active_record', before: :load_config_initializers do
ActiveSupport.on_load :active_record do
Geocoder::Railtie.insert
end
end
rake_tasks do
load "tasks/geocoder.rake"
load "tasks/maxmind.rake"
end
end
end
class Railtie
def self.insert
if defined?(::ActiveRecord)
::ActiveRecord::Base.extend(Model::ActiveRecord)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/kernel_logger.rb | lib/geocoder/kernel_logger.rb | module Geocoder
class KernelLogger
include Singleton
def add(level, message)
return unless log_message_at_level?(level)
case level
when ::Logger::DEBUG, ::Logger::INFO
puts message
when ::Logger::WARN
warn message
when ::Logger::ERROR
raise message
when ::Logger::FATAL
fail message
end
end
private # ----------------------------------------------------------------
def log_message_at_level?(level)
level >= Geocoder.config.kernel_logger_level
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/configuration.rb | lib/geocoder/configuration.rb | require 'singleton'
require 'geocoder/configuration_hash'
require 'geocoder/util'
module Geocoder
##
# Configuration options should be set by passing a hash:
#
# Geocoder.configure(
# :timeout => 5,
# :lookup => :yandex,
# :api_key => "2a9fsa983jaslfj982fjasd",
# :units => :km
# )
#
def self.configure(options = nil, &block)
if !options.nil?
Configuration.instance.configure(options)
end
end
##
# Read-only access to the singleton's config data.
#
def self.config
Configuration.instance.data
end
##
# Read-only access to lookup-specific config data.
#
def self.config_for_lookup(lookup_name)
data = config.clone
data.reject!{ |key,value| !Configuration::OPTIONS.include?(key) }
if config.has_key?(lookup_name)
data.merge!(config[lookup_name])
end
data
end
##
# Merge the given hash into a lookup's existing configuration.
#
def self.merge_into_lookup_config(lookup_name, options)
base = Geocoder.config[lookup_name]
Geocoder.configure(lookup_name => base.merge(options))
end
class Configuration
include Singleton
OPTIONS = [
:timeout,
:lookup,
:ip_lookup,
:language,
:host,
:http_headers,
:use_https,
:http_proxy,
:https_proxy,
:api_key,
:cache,
:always_raise,
:units,
:distances,
:basic_auth,
:logger,
:kernel_logger_level,
:cache_options
]
attr_accessor :data
def self.set_defaults
instance.set_defaults
end
def self.initialize
instance.send(:initialize)
end
OPTIONS.each do |o|
define_method o do
@data[o]
end
define_method "#{o}=" do |value|
@data[o] = value
end
end
def configure(options)
Util.recursive_hash_merge(@data, options)
end
def initialize # :nodoc
@data = Geocoder::ConfigurationHash.new
set_defaults
end
def set_defaults
# geocoding options
@data[:timeout] = 3 # geocoding service timeout (secs)
@data[:lookup] = :nominatim # name of street address geocoding service (symbol)
@data[:ip_lookup] = :ipinfo_io # name of IP address geocoding service (symbol)
@data[:language] = :en # ISO-639 language code
@data[:http_headers] = {} # HTTP headers for lookup
@data[:use_https] = true # use HTTPS for lookup requests? (if supported)
@data[:http_proxy] = nil # HTTP proxy server (user:pass@host:port)
@data[:https_proxy] = nil # HTTPS proxy server (user:pass@host:port)
@data[:api_key] = nil # API key for geocoding service
@data[:basic_auth] = {} # user and password for basic auth ({:user => "user", :password => "password"})
@data[:logger] = :kernel # :kernel or Logger instance
@data[:kernel_logger_level] = ::Logger::WARN # log level, if kernel logger is used
# exceptions that should not be rescued by default
# (if you want to implement custom error handling);
# supports SocketError and Timeout::Error
@data[:always_raise] = []
# calculation options
@data[:units] = :mi # :mi or :km
@data[:distances] = :linear # :linear or :spherical
# Set the default values for the caching mechanism
# By default, the cache keys will not expire as IP addresses and phyiscal
# addresses will rarely change.
@data[:cache] = nil # cache object (must respond to #[], #[]=, and optionally #keys)
@data[:cache_prefix] = nil # - DEPRECATED - prefix (string) to use for all cache keys
@data[:cache_options] = {
prefix: 'geocoder:',
expiration: nil
}
end
instance_eval(OPTIONS.map do |option|
o = option.to_s
<<-EOS
def #{o}
instance.data[:#{o}]
end
def #{o}=(value)
instance.data[:#{o}] = value
end
EOS
end.join("\n\n"))
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/ip_address.rb | lib/geocoder/ip_address.rb | require 'resolv'
module Geocoder
class IpAddress < String
PRIVATE_IPS = [
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
].map { |ip| IPAddr.new(ip) }.freeze
def initialize(ip)
ip = ip.to_string if ip.is_a?(IPAddr)
if ip.is_a?(Hash)
super(**ip)
else
super(ip)
end
end
def internal?
loopback? || private?
end
def loopback?
valid? and !!(self == "0.0.0.0" or self.match(/\A127\./) or self == "::1")
end
def private?
valid? && PRIVATE_IPS.any? { |ip| ip.include?(self) }
end
def valid?
ip = self[/(?<=\[)(.*?)(?=\])/] || self
!!((ip =~ Resolv::IPv4::Regex) || (ip =~ Resolv::IPv6::Regex))
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/cli.rb | lib/geocoder/cli.rb | require 'geocoder'
require 'optparse'
module Geocoder
class Cli
def self.run(args, out = STDOUT)
show_url = false
show_json = false
# remove arguments that are probably coordinates so they are not
# processed as arguments (eg: -31.96047031,115.84274631)
coords = args.select{ |i| i.match(/^-\d/) }
args -= coords
OptionParser.new{ |opts|
opts.banner = "Usage:\n geocode [options] <location>"
opts.separator "\nOptions: "
opts.on("-k <key>", "--key <key>",
"Key for geocoding API (usually optional). Enclose multi-part keys in quotes and separate parts by spaces") do |key|
if (key_parts = key.split(/\s+/)).size > 1
Geocoder.configure(:api_key => key_parts)
else
Geocoder.configure(:api_key => key)
end
end
opts.on("-l <language>", "--language <language>",
"Language of output (see API docs for valid choices)") do |language|
Geocoder.configure(:language => language)
end
opts.on("-p <proxy>", "--proxy <proxy>",
"HTTP proxy server to use (user:pass@host:port)") do |proxy|
Geocoder.configure(:http_proxy => proxy)
end
opts.on("-s <service>", Geocoder::Lookup.all_services_except_test, "--service <service>",
"Geocoding service: #{Geocoder::Lookup.all_services_except_test * ', '}") do |service|
Geocoder.configure(:lookup => service.to_sym)
Geocoder.configure(:ip_lookup => service.to_sym)
end
opts.on("-t <seconds>", "--timeout <seconds>",
"Maximum number of seconds to wait for API response") do |timeout|
Geocoder.configure(:timeout => timeout.to_i)
end
opts.on("-j", "--json", "Print API's raw JSON response") do
show_json = true
end
opts.on("-u", "--url", "Print URL for API query instead of result") do
show_url = true
end
opts.on_tail("-v", "--version", "Print version number") do
require "geocoder/version"
out << "Geocoder #{Geocoder::VERSION}\n"
exit
end
opts.on_tail("-h", "--help", "Print this help") do
out << "Look up geographic information about a location.\n\n"
out << opts
out << "\nCreated and maintained by Alex Reisner, available under the MIT License.\n"
out << "Report bugs and contribute at https://github.com/alexreisner/geocoder\n"
exit
end
}.parse!(args)
# concatenate args with coords that might have been removed
# before option processing
query = (args + coords).join(" ")
if query == ""
out << "Please specify a location (run `geocode -h` for more info).\n"
exit 1
end
if show_url and show_json
out << "You can only specify one of -j and -u.\n"
exit 2
end
if show_url
q = Geocoder::Query.new(query)
out << q.url + "\n"
exit 0
end
if show_json
q = Geocoder::Query.new(query)
out << q.lookup.send(:fetch_raw_data, q) + "\n"
exit 0
end
if (result = Geocoder.search(query).first)
nominatim = Geocoder::Lookup.get(:nominatim)
lines = [
["Latitude", result.latitude],
["Longitude", result.longitude],
["Full address", result.address],
["City", result.city],
["State/province", result.state],
["Postal code", result.postal_code],
["Country", result.country],
["Map", nominatim.map_link_url(result.coordinates)],
]
lines.each do |line|
out << (line[0] + ": ").ljust(18) + line[1].to_s + "\n"
end
exit 0
else
out << "Location '#{query}' not found.\n"
exit 1
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/calculations.rb | lib/geocoder/calculations.rb | module Geocoder
module Calculations
extend self
##
# Compass point names, listed clockwise starting at North.
#
# If you want bearings named using more, fewer, or different points
# override Geocoder::Calculations.COMPASS_POINTS with your own array.
#
COMPASS_POINTS = %w[N NE E SE S SW W NW]
##
# Conversion factor: multiply by kilometers to get miles.
#
KM_IN_MI = 0.621371192
##
# Conversion factor: multiply by nautical miles to get miles.
#
KM_IN_NM = 0.539957
##
# Conversion factor: multiply by radians to get degrees.
#
DEGREES_PER_RADIAN = 57.2957795
##
# Radius of the Earth, in kilometers.
# Value taken from: http://en.wikipedia.org/wiki/Earth_radius
#
EARTH_RADII = {km: 6371.0}
EARTH_RADII[:mi] = EARTH_RADII[:km] * KM_IN_MI
EARTH_RADII[:nm] = EARTH_RADII[:km] * KM_IN_NM
EARTH_RADIUS = EARTH_RADII[:km] # TODO: deprecate this constant (use `EARTH_RADII[:km]`)
# Not a number constant
NAN = defined?(::Float::NAN) ? ::Float::NAN : 0 / 0.0
##
# Returns true if all given arguments are valid latitude/longitude values.
#
def coordinates_present?(*args)
args.each do |a|
# note that Float::NAN != Float::NAN
# still, this could probably be improved:
return false if (!a.is_a?(Numeric) or a.to_s == "NaN")
end
true
end
##
# Distance spanned by one degree of latitude in the given units.
#
def latitude_degree_distance(units = nil)
2 * Math::PI * earth_radius(units) / 360
end
##
# Distance spanned by one degree of longitude at the given latitude.
# This ranges from around 69 miles at the equator to zero at the poles.
#
def longitude_degree_distance(latitude, units = nil)
latitude_degree_distance(units) * Math.cos(to_radians(latitude))
end
##
# Distance between two points on Earth (Haversine formula).
# Takes two points and an options hash.
# The points are given in the same way that points are given to all
# Geocoder methods that accept points as arguments. They can be:
#
# * an array of coordinates ([lat,lon])
# * a geocodable address (string)
# * a geocoded object (one which implements a +to_coordinates+ method
# which returns a [lat,lon] array
#
# The options hash supports:
#
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>
# Use Geocoder.configure(:units => ...) to configure default units.
#
def distance_between(point1, point2, options = {})
# convert to coordinate arrays
point1 = extract_coordinates(point1)
point2 = extract_coordinates(point2)
# convert degrees to radians
point1 = to_radians(point1)
point2 = to_radians(point2)
# compute deltas
dlat = point2[0] - point1[0]
dlon = point2[1] - point1[1]
a = (Math.sin(dlat / 2))**2 + Math.cos(point1[0]) *
(Math.sin(dlon / 2))**2 * Math.cos(point2[0])
c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))
c * earth_radius(options[:units])
end
##
# Bearing between two points on Earth.
# Returns a number of degrees from due north (clockwise).
#
# See Geocoder::Calculations.distance_between for
# ways of specifying the points. Also accepts an options hash:
#
# * <tt>:method</tt> - <tt>:linear</tt> or <tt>:spherical</tt>;
# the spherical method is "correct" in that it returns the shortest path
# (one along a great circle) but the linear method is less confusing
# (returns due east or west when given two points with the same latitude).
# Use Geocoder.configure(:distances => ...) to configure calculation method.
#
# Based on: http://www.movable-type.co.uk/scripts/latlong.html
#
def bearing_between(point1, point2, options = {})
# set default options
options[:method] ||= Geocoder.config.distances
options[:method] = :linear unless options[:method] == :spherical
# convert to coordinate arrays
point1 = extract_coordinates(point1)
point2 = extract_coordinates(point2)
# convert degrees to radians
point1 = to_radians(point1)
point2 = to_radians(point2)
# compute deltas
dlat = point2[0] - point1[0]
dlon = point2[1] - point1[1]
case options[:method]
when :linear
y = dlon
x = dlat
when :spherical
y = Math.sin(dlon) * Math.cos(point2[0])
x = Math.cos(point1[0]) * Math.sin(point2[0]) -
Math.sin(point1[0]) * Math.cos(point2[0]) * Math.cos(dlon)
end
bearing = Math.atan2(x,y)
# Answer is in radians counterclockwise from due east.
# Convert to degrees clockwise from due north:
(90 - to_degrees(bearing) + 360) % 360
end
##
# Translate a bearing (float) into a compass direction (string, eg "North").
#
def compass_point(bearing, points = COMPASS_POINTS)
seg_size = 360.0 / points.size
points[((bearing + (seg_size / 2)) % 360) / seg_size]
end
##
# Compute the geographic center (aka geographic midpoint, center of
# gravity) for an array of geocoded objects and/or [lat,lon] arrays
# (can be mixed). Any objects missing coordinates are ignored. Follows
# the procedure documented at http://www.geomidpoint.com/calculation.html.
#
def geographic_center(points)
# convert objects to [lat,lon] arrays and convert degrees to radians
coords = points.map{ |p| to_radians(extract_coordinates(p)) }
# convert to Cartesian coordinates
x = []; y = []; z = []
coords.each do |p|
x << Math.cos(p[0]) * Math.cos(p[1])
y << Math.cos(p[0]) * Math.sin(p[1])
z << Math.sin(p[0])
end
# compute average coordinate values
xa, ya, za = [x,y,z].map do |c|
c.inject(0){ |tot,i| tot += i } / c.size.to_f
end
# convert back to latitude/longitude
lon = Math.atan2(ya, xa)
hyp = Math.sqrt(xa**2 + ya**2)
lat = Math.atan2(za, hyp)
# return answer in degrees
to_degrees [lat, lon]
end
##
# Returns coordinates of the southwest and northeast corners of a box
# with the given point at its center. The radius is the shortest distance
# from the center point to any side of the box (the length of each side
# is twice the radius).
#
# This is useful for finding corner points of a map viewport, or for
# roughly limiting the possible solutions in a geo-spatial search
# (ActiveRecord queries use it thusly).
#
# See Geocoder::Calculations.distance_between for
# ways of specifying the point. Also accepts an options hash:
#
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>.
# Use Geocoder.configure(:units => ...) to configure default units.
#
def bounding_box(point, radius, options = {})
lat,lon = extract_coordinates(point)
radius = radius.to_f
[
lat - (radius / latitude_degree_distance(options[:units])),
lon - (radius / longitude_degree_distance(lat, options[:units])),
lat + (radius / latitude_degree_distance(options[:units])),
lon + (radius / longitude_degree_distance(lat, options[:units]))
]
end
##
# Random point within a circle of provided radius centered
# around the provided point
# Takes one point, one radius, and an options hash.
# The points are given in the same way that points are given to all
# Geocoder methods that accept points as arguments. They can be:
#
# * an array of coordinates ([lat,lon])
# * a geocodable address (string)
# * a geocoded object (one which implements a +to_coordinates+ method
# which returns a [lat,lon] array
#
# The options hash supports:
#
# * <tt>:units</tt> - <tt>:mi</tt> or <tt>:km</tt>
# Use Geocoder.configure(:units => ...) to configure default units.
# * <tt>:seed</tt> - The seed for the random number generator
def random_point_near(center, radius, options = {})
random = Random.new(options[:seed] || Random.new_seed)
# convert to coordinate arrays
center = extract_coordinates(center)
earth_circumference = 2 * Math::PI * earth_radius(options[:units])
max_degree_delta = 360.0 * (radius / earth_circumference)
# random bearing in radians
theta = 2 * Math::PI * random.rand
# random radius, use the square root to ensure a uniform
# distribution of points over the circle
r = Math.sqrt(random.rand) * max_degree_delta
delta_lat, delta_long = [r * Math.cos(theta), r * Math.sin(theta)]
[center[0] + delta_lat, center[1] + delta_long]
end
##
# Given a start point, heading (in degrees), and distance, provides
# an endpoint.
# The starting point is given in the same way that points are given to all
# Geocoder methods that accept points as arguments. It can be:
#
# * an array of coordinates ([lat,lon])
# * a geocodable address (string)
# * a geocoded object (one which implements a +to_coordinates+ method
# which returns a [lat,lon] array
#
def endpoint(start, heading, distance, options = {})
radius = earth_radius(options[:units])
start = extract_coordinates(start)
# convert degrees to radians
start = to_radians(start)
lat = start[0]
lon = start[1]
heading = to_radians(heading)
distance = distance.to_f
end_lat = Math.asin(Math.sin(lat)*Math.cos(distance/radius) +
Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading))
end_lon = lon+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat),
Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat))
to_degrees [end_lat, end_lon]
end
##
# Convert degrees to radians.
# If an array (or multiple arguments) is passed,
# converts each value and returns array.
#
def to_radians(*args)
args = args.first if args.first.is_a?(Array)
if args.size == 1
args.first * (Math::PI / 180)
else
args.map{ |i| to_radians(i) }
end
end
##
# Convert radians to degrees.
# If an array (or multiple arguments) is passed,
# converts each value and returns array.
#
def to_degrees(*args)
args = args.first if args.first.is_a?(Array)
if args.size == 1
(args.first * 180.0) / Math::PI
else
args.map{ |i| to_degrees(i) }
end
end
def distance_to_radians(distance, units = nil)
distance.to_f / earth_radius(units)
end
def radians_to_distance(radians, units = nil)
radians * earth_radius(units)
end
##
# Convert miles to kilometers.
#
def to_kilometers(mi)
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.to_kilometers is deprecated and will be removed in Geocoder 1.5.0. Please multiply by MI_IN_KM instead.")
mi * mi_in_km
end
##
# Convert kilometers to miles.
#
def to_miles(km)
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.to_miles is deprecated and will be removed in Geocoder 1.5.0. Please multiply by KM_IN_MI instead.")
km * KM_IN_MI
end
##
# Convert kilometers to nautical miles.
#
def to_nautical_miles(km)
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.to_nautical_miles is deprecated and will be removed in Geocoder 1.5.0. Please multiply by KM_IN_NM instead.")
km * KM_IN_NM
end
##
# Radius of the Earth in the given units (:mi or :km).
# Use Geocoder.configure(:units => ...) to configure default units.
#
def earth_radius(units = nil)
EARTH_RADII[units || Geocoder.config.units]
end
##
# Conversion factor: km to mi.
#
def km_in_mi
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.km_in_mi is deprecated and will be removed in Geocoder 1.5.0. Please use the constant KM_IN_MI instead.")
KM_IN_MI
end
##
# Conversion factor: km to nm.
#
def km_in_nm
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.km_in_nm is deprecated and will be removed in Geocoder 1.5.0. Please use the constant KM_IN_NM instead.")
KM_IN_NM
end
##
# Conversion factor: mi to km.
#
def mi_in_km
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.mi_in_km is deprecated and will be removed in Geocoder 1.5.0. Please use 1.0 / KM_IN_MI instead.")
1.0 / KM_IN_MI
end
##
# Conversion factor: nm to km.
#
def nm_in_km
Geocoder.log(:warn, "DEPRECATION WARNING: Geocoder::Calculations.nm_in_km is deprecated and will be removed in Geocoder 1.5.0. Please use 1.0 / KM_IN_NM instead.")
1.0 / KM_IN_NM
end
##
# Takes an object which is a [lat,lon] array, a geocodable string,
# or an object that implements +to_coordinates+ and returns a
# [lat,lon] array. Note that if a string is passed this may be a slow-
# running method and may return nil.
#
def extract_coordinates(point)
case point
when Array
if point.size == 2
lat, lon = point
if !lat.nil? && lat.respond_to?(:to_f) and
!lon.nil? && lon.respond_to?(:to_f)
then
return [ lat.to_f, lon.to_f ]
end
end
when String
point = Geocoder.coordinates(point) and return point
else
if point.respond_to?(:to_coordinates)
if Array === array = point.to_coordinates
return extract_coordinates(array)
end
end
end
[ NAN, NAN ]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/configuration_hash.rb | lib/geocoder/configuration_hash.rb | module Geocoder
class ConfigurationHash < Hash
def method_missing(meth, *args, &block)
has_key?(meth) ? self[meth] : super
end
def respond_to_missing?(meth, include_private = false)
has_key?(meth) || super
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/request.rb | lib/geocoder/request.rb | require 'ipaddr'
module Geocoder
module Request
# The location() method is vulnerable to trivial IP spoofing.
# Don't use it in authorization/authentication code, or any
# other security-sensitive application. Use safe_location
# instead.
def location
@location ||= Geocoder.search(geocoder_spoofable_ip, ip_address: true).first
end
# This safe_location() protects you from trivial IP spoofing.
# For requests that go through a proxy that you haven't
# whitelisted as trusted in your Rack config, you will get the
# location for the IP of the last untrusted proxy in the chain,
# not the original client IP. You WILL NOT get the location
# corresponding to the original client IP for any request sent
# through a non-whitelisted proxy.
def safe_location
@safe_location ||= Geocoder.search(ip, ip_address: true).first
end
# There's a whole zoo of nonstandard headers added by various
# proxy softwares to indicate original client IP.
# ANY of these can be trivially spoofed!
# (except REMOTE_ADDR, which should by set by your server,
# and is included at the end as a fallback.
# Order does matter: we're following the convention established in
# ActionDispatch::RemoteIp::GetIp::calculate_ip()
# https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/remote_ip.rb
# where the forwarded_for headers, possibly containing lists,
# are arbitrarily preferred over headers expected to contain a
# single address.
GEOCODER_CANDIDATE_HEADERS = ['HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'HTTP_X_CLIENT_IP',
'HTTP_CLIENT_IP',
'HTTP_X_REAL_IP',
'HTTP_X_CLUSTER_CLIENT_IP',
'REMOTE_ADDR']
def geocoder_spoofable_ip
# We could use a more sophisticated IP-guessing algorithm here,
# in which we'd try to resolve the use of different headers by
# different proxies. The idea is that by comparing IPs repeated
# in different headers, you can sometimes decide which header
# was used by a proxy further along in the chain, and thus
# prefer the headers used earlier. However, the gains might not
# be worth the performance tradeoff, since this method is likely
# to be called on every request in a lot of applications.
GEOCODER_CANDIDATE_HEADERS.each do |header|
if @env.has_key? header
addrs = geocoder_split_ip_addresses(@env[header])
addrs = geocoder_remove_port_from_addresses(addrs)
addrs = geocoder_reject_non_ipv4_addresses(addrs)
addrs = geocoder_reject_trusted_ip_addresses(addrs)
return addrs.first if addrs.any?
end
end
@env['REMOTE_ADDR']
end
private
def geocoder_split_ip_addresses(ip_addresses)
ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : []
end
# use Rack's trusted_proxy?() method to filter out IPs that have
# been configured as trusted; includes private ranges by
# default. (we don't want every lookup to return the location
# of our own proxy/load balancer)
def geocoder_reject_trusted_ip_addresses(ip_addresses)
ip_addresses.reject { |ip| trusted_proxy?(ip) }
end
def geocoder_remove_port_from_addresses(ip_addresses)
ip_addresses.map do |ip|
# IPv4
if ip.count('.') > 0
ip.split(':').first
# IPv6 bracket notation
elsif match = ip.match(/\[(\S+)\]/)
match.captures.first
# IPv6 bare notation
else
ip
end
end
end
def geocoder_reject_non_ipv4_addresses(ip_addresses)
ips = []
for ip in ip_addresses
begin
valid_ip = IPAddr.new(ip)
rescue
valid_ip = false
end
ips << valid_ip.to_s if valid_ip
end
return ips.any? ? ips : ip_addresses
end
end
end
ActionDispatch::Request.__send__(:include, Geocoder::Request) if defined?(ActionDispatch::Request)
Rack::Request.__send__(:include, Geocoder::Request) if defined?(Rack::Request)
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookup.rb | lib/geocoder/lookup.rb | require "geocoder/lookups/test"
module Geocoder
module Lookup
extend self
##
# Array of valid Lookup service names.
#
def all_services
street_services + ip_services
end
##
# Array of valid Lookup service names, excluding :test.
#
def all_services_except_test
all_services - [:test]
end
##
# Array of valid Lookup service names, excluding any that do not build their own HTTP requests.
# For example, Amazon Location Service uses the AWS gem, not HTTP REST requests, to fetch data.
#
def all_services_with_http_requests
all_services_except_test - [:amazon_location_service, :maxmind_local, :geoip2, :ip2location_lite]
end
##
# All street address lookup services, default first.
#
def street_services
@street_services ||= [
:location_iq,
:azure,
:esri,
:google,
:google_premier,
:google_places_details,
:google_places_search,
:bing,
:geocoder_ca,
:yandex,
:nationaal_georegister_nl,
:nominatim,
:mapbox,
:mapquest,
:uk_ordnance_survey_names,
:opencagedata,
:pelias,
:pdok_nl,
:pickpoint,
:here,
:baidu,
:tencent,
:geocodio,
:smarty_streets,
:postcode_anywhere_uk,
:postcodes_io,
:geoportail_lu,
:ban_data_gouv_fr,
:test,
:latlon,
:amap,
:osmnames,
:melissa_street,
:amazon_location_service,
:geoapify,
:photon,
:twogis,
:pc_miler
]
end
##
# All IP address lookup services, default first.
#
def ip_services
@ip_services ||= [
:baidu_ip,
:abstract_api,
:freegeoip,
:geoip2,
:maxmind,
:maxmind_local,
:telize,
:pointpin,
:maxmind_geoip2,
:ipinfo_io,
:ipinfo_io_lite,
:ipregistry,
:ipapi_com,
:ipdata_co,
:db_ip_com,
:ipstack,
:ip2location,
:ipgeolocation,
:ipqualityscore,
:ipbase,
:ip2location_io,
:ip2location_lite
]
end
attr_writer :street_services, :ip_services
##
# Retrieve a Lookup object from the store.
# Use this instead of Geocoder::Lookup::X.new to get an
# already-configured Lookup object.
#
def get(name)
@services = {} unless defined?(@services)
@services[name] = spawn(name) unless @services.include?(name)
@services[name]
end
private # -----------------------------------------------------------------
##
# Spawn a Lookup of the given name.
#
def spawn(name)
if all_services.include?(name)
name = name.to_s
instantiate_lookup(name)
else
valids = all_services.map(&:inspect).join(", ")
raise ConfigurationError, "Please specify a valid lookup for Geocoder " +
"(#{name.inspect} is not one of: #{valids})."
end
end
##
# Convert an "underscore" version of a name into a "class" version.
#
def classify_name(filename)
filename.to_s.split("_").map{ |i| i[0...1].upcase + i[1..-1] }.join
end
##
# Safely instantiate Lookup
#
def instantiate_lookup(name)
class_name = classify_name(name)
begin
Geocoder::Lookup.const_get(class_name, inherit=false)
rescue NameError
require "geocoder/lookups/#{name}"
end
Geocoder::Lookup.const_get(class_name).new
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/cache.rb | lib/geocoder/cache.rb | Dir["#{__dir__}/cache_stores/*.rb"].each {|file| require file }
module Geocoder
class Cache
def initialize(store, config)
@class = (Geocoder::CacheStore.const_get("#{store.class}", false) rescue Geocoder::CacheStore::Generic)
@store_service = @class.new(store, config)
end
##
# Read from the Cache.
#
def [](url)
interpret store_service.read(url)
rescue => e
Geocoder.log(:warn, "Geocoder cache read error: #{e}")
end
##
# Write to the Cache.
#
def []=(url, value)
store_service.write(url, value)
rescue => e
Geocoder.log(:warn, "Geocoder cache write error: #{e}")
end
##
# Delete cache entry for given URL,
# or pass <tt>:all</tt> to clear all URLs.
#
def expire(url)
if url == :all
if store_service.respond_to?(:keys)
urls.each{ |u| expire(u) }
else
raise(NoMethodError, "The Geocoder cache store must implement `#keys` for `expire(:all)` to work")
end
else
expire_single_url(url)
end
end
private # ----------------------------------------------------------------
def store_service; @store_service; end
##
# Array of keys with the currently configured prefix
# that have non-nil values.
#
def keys
store_service.keys
end
##
# Array of cached URLs.
#
def urls
store_service.urls
end
##
# Clean up value before returning. Namely, convert empty string to nil.
# (Some key/value stores return empty string instead of nil.)
#
def interpret(value)
value == "" ? nil : value
end
def expire_single_url(url)
store_service.remove(url)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/util.rb | lib/geocoder/util.rb | # frozen_string_literal: true
module Geocoder
module Util
#
# Recursive version of Hash#merge!
#
# Adds the contents of +h2+ to +h1+,
# merging entries in +h1+ with duplicate keys with those from +h2+.
#
# Compared with Hash#merge!, this method supports nested hashes.
# When both +h1+ and +h2+ contains an entry with the same key,
# it merges and returns the values from both hashes.
#
# h1 = {"a" => 100, "b" => 200, "c" => {"c1" => 12, "c2" => 14}}
# h2 = {"b" => 254, "c" => {"c1" => 16, "c3" => 94}}
# recursive_hash_merge(h1, h2) #=> {"a" => 100, "b" => 254, "c" => {"c1" => 16, "c2" => 14, "c3" => 94}}
#
# Simply using Hash#merge! would return
#
# h1.merge!(h2) #=> {"a" => 100, "b" = >254, "c" => {"c1" => 16, "c3" => 94}}
#
def self.recursive_hash_merge(h1, h2)
h1.merge!(h2) do |_key, oldval, newval|
oldval.class == h1.class ? self.recursive_hash_merge(oldval, newval) : newval
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/maxmind.rb | lib/geocoder/lookups/maxmind.rb | require 'geocoder/lookups/base'
require 'geocoder/results/maxmind'
require 'csv'
module Geocoder::Lookup
class Maxmind < Base
def name
"MaxMind"
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://geoip.maxmind.com/#{service_code}?"
end
##
# Return the name of the configured service, or raise an exception.
#
def configured_service!
if s = configuration[:service] and services.keys.include?(s)
return s
else
raise(
Geocoder::ConfigurationError,
"When using MaxMind you MUST specify a service name: " +
"Geocoder.configure(:maxmind => {:service => ...}), " +
"where '...' is one of: #{services.keys.inspect}"
)
end
end
def service_code
services[configured_service!]
end
def service_response_fields_count
Geocoder::Result::Maxmind.field_names[configured_service!].size
end
def data_contains_error?(parsed_data)
# if all fields given then there is an error
parsed_data.size == service_response_fields_count and !parsed_data.last.nil?
end
##
# Service names mapped to code used in URL.
#
def services
{
:country => "a",
:city => "b",
:city_isp_org => "f",
:omni => "e"
}
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result] if query.internal_ip_address?
doc = fetch_data(query)
if doc and doc.is_a?(Array)
if !data_contains_error?(doc)
return [doc]
elsif doc.last == "INVALID_LICENSE_KEY"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "Invalid MaxMind API key.")
end
end
return []
end
def parse_raw_data(raw_data)
# Maxmind just returns text/plain as csv format but according to documentation,
# we get ISO-8859-1 encoded string. We need to convert it.
CSV.parse_line raw_data.force_encoding("ISO-8859-1").encode("UTF-8")
end
def reserved_result
",,,,0,0,0,0,,,".split(",")
end
def query_url_params(query)
{
:l => configuration.api_key,
:i => query.sanitized_text
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/test.rb | lib/geocoder/lookups/test.rb | require 'geocoder/lookups/base'
require 'geocoder/results/test'
module Geocoder
module Lookup
class Test < Base
def name
"Test"
end
def self.add_stub(query_text, results)
stubs[query_text] = results
end
def self.set_default_stub(results)
@default_stub = results
end
def self.read_stub(query_text)
@default_stub ||= nil
stubs.fetch(query_text) {
return @default_stub unless @default_stub.nil?
raise ArgumentError, "unknown stub request #{query_text}"
}
end
def self.stubs
@stubs ||= {}
end
def self.delete_stub(query_text)
stubs.delete(query_text)
end
def self.reset
@stubs = {}
@default_stub = nil
end
private
def results(query)
Geocoder::Lookup::Test.read_stub(query.text)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/photon.rb | lib/geocoder/lookups/photon.rb | require 'geocoder/lookups/base'
require 'geocoder/results/photon'
module Geocoder::Lookup
class Photon < Base
def name
'Photon'
end
private # ---------------------------------------------------------------
def supported_protocols
[:https]
end
def base_query_url(query)
host = configuration[:host] || 'photon.komoot.io'
method = query.reverse_geocode? ? 'reverse' : 'api'
"#{protocol}://#{host}/#{method}?"
end
def results(query)
return [] unless (doc = fetch_data(query))
return [] unless doc['type'] == 'FeatureCollection'
return [] unless doc['features'] || doc['features'].present?
doc['features']
end
def query_url_params(query)
lang = query.language || configuration.language
params = { lang: lang, limit: query.options[:limit] }
if query.reverse_geocode?
params.merge!(query_url_params_reverse(query))
else
params.merge!(query_url_params_coordinates(query))
end
params.merge!(super)
end
def query_url_params_coordinates(query)
params = { q: query.sanitized_text }
if (bias = query.options[:bias])
params.merge!(lat: bias[:latitude], lon: bias[:longitude], location_bias_scale: bias[:scale])
end
if (filter = query_url_params_coordinates_filter(query))
params.merge!(filter)
end
params
end
def query_url_params_coordinates_filter(query)
filter = query.options[:filter]
return unless filter
bbox = filter[:bbox]
{
bbox: bbox.is_a?(Array) ? bbox.join(',') : bbox,
osm_tag: filter[:osm_tag]
}
end
def query_url_params_reverse(query)
params = { lat: query.coordinates[0], lon: query.coordinates[1], radius: query.options[:radius] }
if (dsort = query.options[:distance_sort])
params[:distance_sort] = dsort ? 'true' : 'false'
end
if (filter = query_url_params_reverse_filter(query))
params.merge!(filter)
end
params
end
def query_url_params_reverse_filter(query)
filter = query.options[:filter]
return unless filter
{ query_string_filter: filter[:string] }
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/smarty_streets.rb | lib/geocoder/lookups/smarty_streets.rb | require 'geocoder/lookups/base'
require 'geocoder/results/smarty_streets'
module Geocoder::Lookup
class SmartyStreets < Base
def name
"SmartyStreets"
end
def required_api_key_parts
%w(auth-id auth-token)
end
# required by API as of 26 March 2015
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
if international?(query)
"#{protocol}://international-street.api.smartystreets.com/verify?"
elsif zipcode_only?(query)
"#{protocol}://us-zipcode.api.smartystreets.com/lookup?"
else
"#{protocol}://us-street.api.smartystreets.com/street-address?"
end
end
def zipcode_only?(query)
!query.text.is_a?(Array) and query.to_s.strip =~ /\A\d{5}(-\d{4})?\Z/
end
def international?(query)
!query.options[:country].nil?
end
def query_url_params(query)
params = {}
if international?(query)
params[:freeform] = query.sanitized_text
params[:country] = query.options[:country]
params[:geocode] = true
elsif zipcode_only?(query)
params[:zipcode] = query.sanitized_text
else
params[:street] = query.sanitized_text
end
if configuration.api_key.is_a?(Array)
params[:"auth-id"] = configuration.api_key[0]
params[:"auth-token"] = configuration.api_key[1]
else
params[:"auth-token"] = configuration.api_key
end
params.merge(super)
end
def results(query)
doc = fetch_data(query) || []
if doc.is_a?(Hash) and doc.key?('status') # implies there's an error
return []
else
return doc
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/amazon_location_service.rb | lib/geocoder/lookups/amazon_location_service.rb | require 'geocoder/lookups/base'
require 'geocoder/results/amazon_location_service'
module Geocoder::Lookup
class AmazonLocationService < Base
def results(query)
params = query.options.dup
# index_name is required
# Aws::ParamValidator raises ArgumentError on missing required keys
params.merge!(index_name: configuration[:index_name])
# Aws::ParamValidator raises ArgumentError on unexpected keys
params.delete(:lookup)
# Inherit language from configuration
params.merge!(language: configuration[:language])
resp = if query.reverse_geocode?
client.search_place_index_for_position(params.merge(position: query.coordinates.reverse))
else
client.search_place_index_for_text(params.merge(text: query.text))
end
resp.results
end
private
def client
return @client if @client
require_sdk
keys = configuration.api_key
if keys
@client = Aws::LocationService::Client.new(**{
region: keys[:region],
access_key_id: keys[:access_key_id],
secret_access_key: keys[:secret_access_key]
}.compact)
else
@client = Aws::LocationService::Client.new
end
end
def require_sdk
begin
require 'aws-sdk-locationservice'
rescue LoadError
raise_error(Geocoder::ConfigurationError) ||
Geocoder.log(
:error,
"Couldn't load the Amazon Location Service SDK. " +
"Install it with: gem install aws-sdk-locationservice -v '~> 1.4'"
)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/geocodio.rb | lib/geocoder/lookups/geocodio.rb | require 'geocoder/lookups/base'
require "geocoder/results/geocodio"
module Geocoder::Lookup
class Geocodio < Base
def name
"Geocodio"
end
def results(query)
return [] unless doc = fetch_data(query)
return doc["results"] if doc['error'].nil?
if doc['error'] == 'Invalid API key'
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "Geocodio service error: invalid API key.")
elsif doc['error'].match(/You have reached your daily maximum/)
raise_error(Geocoder::OverQueryLimitError, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
else
raise_error(Geocoder::InvalidRequest, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
end
[]
end
private # ---------------------------------------------------------------
def base_query_url(query)
path = query.reverse_geocode? ? "reverse" : "geocode"
"#{protocol}://api.geocod.io/v1.6/#{path}?"
end
def query_url_params(query)
{
:api_key => configuration.api_key,
:q => query.sanitized_text
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/google_premier.rb | lib/geocoder/lookups/google_premier.rb | require 'openssl'
require 'base64'
require 'geocoder/lookups/google'
require 'geocoder/results/google_premier'
module Geocoder::Lookup
class GooglePremier < Google
def name
"Google Premier"
end
def required_api_key_parts
["private key"]
end
def query_url(query)
path = "/maps/api/geocode/json?" + url_query_string(query)
"#{protocol}://maps.googleapis.com#{path}&signature=#{sign(path)}"
end
private # ---------------------------------------------------------------
def result_root_attr
'results'
end
def cache_key(query)
"#{protocol}://maps.googleapis.com/maps/api/geocode/json?" + hash_to_query(cache_key_params(query))
end
def cache_key_params(query)
query_url_google_params(query).merge(super).reject do |k,v|
[:key, :client, :channel].include?(k)
end
end
def query_url_params(query)
query_url_google_params(query).merge(super).merge(
:key => nil, # don't use param inherited from Google lookup
:client => configuration.api_key[1],
:channel => configuration.api_key[2]
)
end
def sign(string)
raw_private_key = url_safe_base64_decode(configuration.api_key[0])
digest = OpenSSL::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, raw_private_key, string)
url_safe_base64_encode(raw_signature)
end
def url_safe_base64_decode(base64_string)
Base64.decode64(base64_string.tr('-_', '+/'))
end
def url_safe_base64_encode(raw)
Base64.encode64(raw).tr('+/', '-_').strip
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/latlon.rb | lib/geocoder/lookups/latlon.rb | require 'geocoder/lookups/base'
require 'geocoder/results/latlon'
module Geocoder::Lookup
class Latlon < Base
def name
"LatLon.io"
end
def required_api_key_parts
["api_key"]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://latlon.io/api/v1/#{'reverse_' if query.reverse_geocode?}geocode?"
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['error'].nil?
[doc]
# The API returned a 404 response, which indicates no results found
elsif doc['error']['type'] == 'api_error'
[]
elsif doc['error']['type'] == 'authentication_error'
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "LatLon.io service error: invalid API key.")
else
[]
end
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def query_url_params(query)
if query.reverse_geocode?
{
:token => configuration.api_key,
:lat => query.coordinates[0],
:lon => query.coordinates[1]
}.merge(super)
else
{
:token => configuration.api_key,
:address => query.sanitized_text
}.merge(super)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/telize.rb | lib/geocoder/lookups/telize.rb | require 'geocoder/lookups/base'
require 'geocoder/results/telize'
module Geocoder::Lookup
class Telize < Base
def name
"Telize"
end
def required_api_key_parts
configuration[:host] ? [] : ["key"]
end
def query_url(query)
if configuration[:host]
"#{protocol}://#{configuration[:host]}/location/#{query.sanitized_text}"
else
"#{protocol}://telize-v1.p.rapidapi.com/location/#{query.sanitized_text}?rapidapi-key=#{api_key}"
end
end
def supported_protocols
[].tap do |array|
array << :https
array << :http if configuration[:host]
end
end
private # ---------------------------------------------------------------
def cache_key(query)
query_url(query)[/(.*)\?.*/, 1]
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
if (doc = fetch_data(query)).nil? or doc['code'] == 401 or empty_result?(doc)
[]
else
[doc]
end
end
def empty_result?(doc)
!doc.is_a?(Hash) or doc.keys == ["ip"]
end
def reserved_result(ip)
{
"ip" => ip,
"latitude" => 0,
"longitude" => 0,
"city" => "",
"timezone" => "",
"asn" => 0,
"region" => "",
"offset" => 0,
"organization" => "",
"country_code" => "",
"country_code3" => "",
"postal_code" => "",
"continent_code" => "",
"country" => "",
"region_code" => ""
}
end
def api_key
configuration.api_key
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/bing.rb | lib/geocoder/lookups/bing.rb | require 'geocoder/lookups/base'
require "geocoder/results/bing"
module Geocoder::Lookup
class Bing < Base
def name
"Bing"
end
def map_link_url(coordinates)
"http://www.bing.com/maps/default.aspx?cp=#{coordinates.join('~')}"
end
def required_api_key_parts
["key"]
end
private # ---------------------------------------------------------------
def base_query_url(query)
text = ERB::Util.url_encode(query.sanitized_text.strip)
url = "#{protocol}://dev.virtualearth.net/REST/v1/Locations/"
if query.reverse_geocode?
url + "#{text}?"
else
if r = query.options[:region]
url << "#{r}/"
end
# use the more forgiving 'unstructured' query format to allow special
# chars, newlines, brackets, typos.
url + "?q=#{text}&"
end
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['statusCode'] == 200
return doc['resourceSets'].first['estimatedTotal'] > 0 ? doc['resourceSets'].first['resources'] : []
elsif doc['statusCode'] == 401 and doc["authenticationResultCode"] == "InvalidCredentials"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "Invalid Bing API key.")
elsif doc['statusCode'] == 403
raise_error(Geocoder::RequestDenied) || Geocoder.log(:warn, "Bing Geocoding API error: Forbidden Request")
elsif [500, 503].include?(doc['statusCode'])
raise_error(Geocoder::ServiceUnavailable) ||
Geocoder.log(:warn, "Bing Geocoding API error: Service Unavailable")
else
Geocoder.log(:warn, "Bing Geocoding API error: #{doc['statusCode']} (#{doc['statusDescription']}).")
end
return []
end
def query_url_params(query)
{
key: configuration.api_key,
culture: (query.language || configuration.language)
}.merge(super)
end
def check_response_for_errors!(response)
super
if server_overloaded?(response)
raise_error(Geocoder::ServiceUnavailable) ||
Geocoder.log(:warn, "Bing Geocoding API error: Service Unavailable")
end
end
def valid_response?(response)
super(response) and not server_overloaded?(response)
end
def server_overloaded?(response)
# Occasionally, the servers processing service requests can be overloaded,
# and you may receive some responses that contain no results for queries that
# you would normally receive a result. To identify this situation,
# check the HTTP headers of the response. If the HTTP header X-MS-BM-WS-INFO is set to 1,
# it is best to wait a few seconds and try again.
response['x-ms-bm-ws-info'].to_i == 1
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipstack.rb | lib/geocoder/lookups/ipstack.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipstack'
module Geocoder::Lookup
class Ipstack < Base
ERROR_CODES = {
404 => Geocoder::InvalidRequest,
101 => Geocoder::InvalidApiKey,
102 => Geocoder::Error,
103 => Geocoder::InvalidRequest,
104 => Geocoder::OverQueryLimitError,
105 => Geocoder::RequestDenied,
301 => Geocoder::InvalidRequest,
302 => Geocoder::InvalidRequest,
303 => Geocoder::RequestDenied,
}
ERROR_CODES.default = Geocoder::Error
def name
"Ipstack"
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://#{host}/#{query.sanitized_text}?"
end
def query_url_params(query)
{
access_key: configuration.api_key
}.merge(super)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
return [] unless doc = fetch_data(query)
if error = doc['error']
code = error['code']
msg = error['info']
raise_error(ERROR_CODES[code], msg ) || Geocoder.log(:warn, "Ipstack Geocoding API error: #{msg}")
return []
end
[doc]
end
def reserved_result(ip)
{
"ip" => ip,
"country_name" => "Reserved",
"country_code" => "RD"
}
end
def host
configuration[:host] || "api.ipstack.com"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipregistry.rb | lib/geocoder/lookups/ipregistry.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipregistry'
module Geocoder::Lookup
class Ipregistry < Base
ERROR_CODES = {
400 => Geocoder::InvalidRequest,
401 => Geocoder::InvalidRequest,
402 => Geocoder::OverQueryLimitError,
403 => Geocoder::InvalidApiKey,
451 => Geocoder::RequestDenied,
500 => Geocoder::Error
}
ERROR_CODES.default = Geocoder::Error
def name
"Ipregistry"
end
def supported_protocols
[:https, :http]
end
private
def base_query_url(query)
"#{protocol}://#{host}/#{query.sanitized_text}?"
end
def cache_key(query)
query_url(query)
end
def host
configuration[:host] || "api.ipregistry.co"
end
def query_url_params(query)
{
key: configuration.api_key
}.merge(super)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
return [] unless (doc = fetch_data(query))
if (error = doc['error'])
code = error['code']
msg = error['message']
raise_error(ERROR_CODES[code], msg ) || Geocoder.log(:warn, "Ipregistry API error: #{msg}")
return []
end
[doc]
end
def reserved_result(ip)
{
"ip" => ip,
"country_name" => "Reserved",
"country_code" => "RD"
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ip2location_lite.rb | lib/geocoder/lookups/ip2location_lite.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ip2location_lite'
module Geocoder
module Lookup
class Ip2locationLite < Base
attr_reader :gem_name
def initialize
unless configuration[:file].nil?
begin
@gem_name = 'ip2location_ruby'
require @gem_name
rescue LoadError
raise "Could not load IP2Location DB dependency. To use the IP2LocationLite lookup you must add the #{@gem_name} gem to your Gemfile or have it installed in your system."
end
end
super
end
def name
'IP2LocationLite'
end
def required_api_key_parts
[]
end
private
def results(query)
return [] unless configuration[:file]
i2l = Ip2location.new.open(configuration[:file].to_s)
result = i2l.get_all(query.to_s)
result.nil? ? [] : [result]
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipdata_co.rb | lib/geocoder/lookups/ipdata_co.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipdata_co'
module Geocoder::Lookup
class IpdataCo < Base
def name
"ipdata.co"
end
def supported_protocols
[:https]
end
def query_url(query)
# Ipdata.co requires that the API key be sent as a query parameter.
# It no longer supports API keys sent as headers.
"#{protocol}://#{host}/#{query.sanitized_text}?api-key=#{configuration.api_key}"
end
private # ---------------------------------------------------------------
def cache_key(query)
query_url(query)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
# note: Ipdata.co returns plain text on bad request
(doc = fetch_data(query)) ? [doc] : []
end
def reserved_result(ip)
{
"ip" => ip,
"city" => "",
"region_code" => "",
"region_name" => "",
"metrocode" => "",
"zipcode" => "",
"latitude" => "0",
"longitude" => "0",
"country_name" => "Reserved",
"country_code" => "RD"
}
end
def host
configuration[:host] || "api.ipdata.co"
end
def check_response_for_errors!(response)
if response.code.to_i == 403
raise_error(Geocoder::RequestDenied) ||
Geocoder.log(:warn, "Geocoding API error: 403 API key does not exist")
else
super(response)
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/mapquest.rb | lib/geocoder/lookups/mapquest.rb | require 'cgi'
require 'geocoder/lookups/base'
require "geocoder/results/mapquest"
module Geocoder::Lookup
class Mapquest < Base
def name
"Mapquest"
end
def required_api_key_parts
["key"]
end
private # ---------------------------------------------------------------
def base_query_url(query)
domain = configuration[:open] ? "open" : "www"
"#{protocol}://#{domain}.mapquestapi.com/geocoding/v1/#{search_type(query)}?"
end
def search_type(query)
query.reverse_geocode? ? "reverse" : "address"
end
def query_url_params(query)
params = { :location => query.sanitized_text }
if key = configuration.api_key
params[:key] = CGI.unescape(key)
end
params.merge(super)
end
# http://www.mapquestapi.com/geocoding/status_codes.html
# http://open.mapquestapi.com/geocoding/status_codes.html
def results(query)
return [] unless doc = fetch_data(query)
return doc["results"][0]['locations'] if doc['info']['statuscode'] == 0 # A successful geocode call
messages = doc['info']['messages'].join
case doc['info']['statuscode']
when 400 # Error with input
raise_error(Geocoder::InvalidRequest, messages) ||
Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
when 403 # Key related error
raise_error(Geocoder::InvalidApiKey, messages) ||
Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
when 500 # Unknown error
raise_error(Geocoder::Error, messages) ||
Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
end
[]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ban_data_gouv_fr.rb | lib/geocoder/lookups/ban_data_gouv_fr.rb | # encoding: utf-8
require 'geocoder/lookups/base'
require 'geocoder/results/ban_data_gouv_fr'
module Geocoder::Lookup
class BanDataGouvFr < Base
def name
"Base Adresse Nationale Française"
end
def map_link_url(coordinates)
"https://www.openstreetmap.org/#map=19/#{coordinates.join('/')}"
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
method = query.reverse_geocode? ? "reverse" : "search"
"#{protocol}://data.geopf.fr/geocodage/#{method}/?"
end
def any_result?(doc)
doc['features'] and doc['features'].any?
end
def results(query)
if doc = fetch_data(query) and any_result?(doc)
[doc]
else
[]
end
end
#### PARAMS ####
def query_url_params(query)
query_ban_datagouv_fr_params(query).merge(super)
end
def query_ban_datagouv_fr_params(query)
query.reverse_geocode? ? reverse_geocode_ban_fr_params(query) : search_geocode_ban_fr_params(query)
end
#### SEARCH GEOCODING PARAMS ####
#
# :q => required, full text search param)
# :limit => force limit number of results returned by raw API
# (default = 5) note : only first result is taken
# in account in geocoder
#
# :autocomplete => pass 0 to disable autocomplete treatment of :q
# (default = 1)
#
# :lat => force filter results around specific lat/lon
#
# :lon => force filter results around specific lat/lon
#
# :type => force filter the returned result type
# (check results for a list of accepted types)
#
# :postcode => force filter results on a specific city post code
#
# :citycode => force filter results on a specific city UUID INSEE code
#
# For up to date doc (in french only) : https://adresse.data.gouv.fr/api/
#
def search_geocode_ban_fr_params(query)
params = {
q: query.sanitized_text
}
unless (limit = query.options[:limit]).nil? || !limit_param_is_valid?(limit)
params[:limit] = limit.to_i
end
unless (autocomplete = query.options[:autocomplete]).nil? || !autocomplete_param_is_valid?(autocomplete)
params[:autocomplete] = autocomplete.to_s
end
unless (type = query.options[:type]).nil? || !type_param_is_valid?(type)
params[:type] = type.downcase
end
unless (postcode = query.options[:postcode]).nil? || !code_param_is_valid?(postcode)
params[:postcode] = postcode.to_s
end
unless (citycode = query.options[:citycode]).nil? || !code_param_is_valid?(citycode)
params[:citycode] = citycode.to_s
end
unless (lat = query.options[:lat]).nil? || !latitude_is_valid?(lat)
params[:lat] = lat
end
unless (lon = query.options[:lon]).nil? || !longitude_is_valid?(lon)
params[:lon] = lon
end
params
end
#### REVERSE GEOCODING PARAMS ####
#
# :lat => required
#
# :lon => required
#
# :type => force returned results type
# (check results for a list of accepted types)
#
def reverse_geocode_ban_fr_params(query)
lat_lon = query.coordinates
params = {
lat: lat_lon.first,
lon: lat_lon.last
}
unless (type = query.options[:type]).nil? || !type_param_is_valid?(type)
params[:type] = type.downcase
end
params
end
def limit_param_is_valid?(param)
param.to_i.positive?
end
def autocomplete_param_is_valid?(param)
[0,1].include?(param.to_i)
end
def type_param_is_valid?(param)
%w(housenumber street locality municipality).include?(param.downcase)
end
def code_param_is_valid?(param)
(1..99999).include?(param.to_i)
end
def latitude_is_valid?(param)
param.to_f <= 90 && param.to_f >= -90
end
def longitude_is_valid?(param)
param.to_f <= 180 && param.to_f >= -180
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/abstract_api.rb | lib/geocoder/lookups/abstract_api.rb | # encoding: utf-8
require 'geocoder/lookups/base'
require 'geocoder/results/abstract_api'
module Geocoder::Lookup
class AbstractApi < Base
def name
"Abstract API"
end
def required_api_key_parts
['api_key']
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://ipgeolocation.abstractapi.com/v1/?"
end
def query_url_params(query)
params = {api_key: configuration.api_key}
ip_address = query.sanitized_text
if ip_address.is_a?(String) && ip_address.length > 0
params[:ip_address] = ip_address
end
params.merge(super)
end
def results(query, reverse = false)
if doc = fetch_data(query)
[doc]
else
[]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/uk_ordnance_survey_names.rb | lib/geocoder/lookups/uk_ordnance_survey_names.rb | require 'geocoder/lookups/base'
require 'geocoder/results/uk_ordnance_survey_names'
module Geocoder::Lookup
class UkOrdnanceSurveyNames < Base
def name
'Ordance Survey Names'
end
def supported_protocols
[:https]
end
def base_query_url(query)
"#{protocol}://api.os.uk/search/names/v1/find?"
end
def required_api_key_parts
["key"]
end
def query_url(query)
base_query_url(query) + url_query_string(query)
end
private # -------------------------------------------------------------
def results(query)
return [] unless doc = fetch_data(query)
return [] if doc['header']['totalresults'].zero?
return doc['results'].map { |r| r['GAZETTEER_ENTRY'] }
end
def query_url_params(query)
{
query: query.sanitized_text,
key: configuration.api_key,
fq: filter
}.merge(super)
end
def local_types
%w[
City
Hamlet
Other_Settlement
Town
Village
Postcode
]
end
def filter
local_types.map { |t| "local_type:#{t}" }.join(' ')
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipqualityscore.rb | lib/geocoder/lookups/ipqualityscore.rb | # encoding: utf-8
require 'geocoder/lookups/base'
require 'geocoder/results/ipqualityscore'
module Geocoder::Lookup
class Ipqualityscore < Base
def name
"IPQualityScore"
end
def required_api_key_parts
['api_key']
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://ipqualityscore.com/api/json/ip/#{configuration.api_key}/#{query.sanitized_text}?"
end
def valid_response?(response)
if (json = parse_json(response.body))
success = json['success']
end
super && success == true
end
def results(query, reverse = false)
return [] unless doc = fetch_data(query)
return [doc] if doc['success']
case doc['message']
when /invalid (.*) key/i
raise_error Geocoder::InvalidApiKey ||
Geocoder.log(:warn, "#{name} API error: invalid api key.")
when /insufficient credits/, /exceeded your request quota/
raise_error Geocoder::OverQueryLimitError ||
Geocoder.log(:warn, "#{name} API error: query limit exceeded.")
when /invalid (.*) address/i
raise_error Geocoder::InvalidRequest ||
Geocoder.log(:warn, "#{name} API error: invalid request.")
end
[doc]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipinfo_io.rb | lib/geocoder/lookups/ipinfo_io.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipinfo_io'
module Geocoder::Lookup
class IpinfoIo < Base
def name
"Ipinfo.io"
end
private # ---------------------------------------------------------------
def base_query_url(query)
url = "#{protocol}://ipinfo.io/#{query.sanitized_text}/geo"
url << "?" if configuration.api_key
url
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
if !(doc = fetch_data(query)).is_a?(Hash) or doc['error']
[]
else
[doc]
end
end
def reserved_result(ip)
{
"ip" => ip,
"bogon" => true
}
end
def query_url_params(query)
{
token: configuration.api_key
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/geocoder_ca.rb | lib/geocoder/lookups/geocoder_ca.rb | require 'geocoder/lookups/base'
require "geocoder/results/geocoder_ca"
module Geocoder::Lookup
class GeocoderCa < Base
def name
"Geocoder.ca"
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://geocoder.ca/?"
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['error'].nil?
return [doc]
elsif doc['error']['code'] == "005"
# "Postal Code is not in the proper Format" => no results, just shut up
else
Geocoder.log(:warn, "Geocoder.ca service error: #{doc['error']['code']} (#{doc['error']['description']}).")
end
return []
end
def query_url_params(query)
params = {
:geoit => "xml",
:jsonp => 1,
:callback => "test",
:auth => configuration.api_key
}.merge(super)
if query.reverse_geocode?
lat,lon = query.coordinates
params[:latt] = lat
params[:longt] = lon
params[:corner] = 1
params[:reverse] = 1
else
params[:locate] = query.sanitized_text
params[:showpostal] = 1
end
params
end
def parse_raw_data(raw_data)
super raw_data[/^test\((.*)\)\;\s*$/, 1]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/pointpin.rb | lib/geocoder/lookups/pointpin.rb | require 'geocoder/lookups/base'
require 'geocoder/results/pointpin'
module Geocoder::Lookup
class Pointpin < Base
def name
"Pointpin"
end
def required_api_key_parts
["key"]
end
def query_url(query)
"#{protocol}://geo.pointp.in/#{configuration.api_key}/json/#{query.sanitized_text}"
end
private # ----------------------------------------------------------------
def cache_key(query)
"#{protocol}://geo.pointp.in/json/#{query.sanitized_text}"
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [] if query.internal_ip_address?
doc = fetch_data(query)
if doc and doc.is_a?(Hash)
if !data_contains_error?(doc)
return [doc]
elsif doc['error']
case doc['error']
when "Invalid IP address"
raise_error(Geocoder::InvalidRequest) || Geocoder.log(:warn, "Invalid Pointpin request.")
when "Invalid API key"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "Invalid Pointpin API key.")
when "Address not found"
Geocoder.log(:warn, "Address not found.")
end
else
raise_error(Geocoder::Error) || Geocoder.log(:warn, "Pointpin server error")
end
end
return []
end
def data_contains_error?(parsed_data)
parsed_data.keys.include?('error')
end
# TODO: replace this hash with what's actually returned by Pointpin
def reserved_result(ip)
{
"ip" => ip,
"city" => "",
"region_code" => "",
"region_name" => "",
"metrocode" => "",
"zipcode" => "",
"latitude" => "0",
"longitude" => "0",
"country_name" => "Reserved",
"country_code" => "RD"
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/pdok_nl.rb | lib/geocoder/lookups/pdok_nl.rb | require 'geocoder/lookups/base'
require "geocoder/results/pdok_nl"
module Geocoder::Lookup
class PdokNl < Base
def name
'pdok NL'
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def cache_key(query)
base_query_url(query) + hash_to_query(query_url_params(query))
end
def base_query_url(query)
"#{protocol}://api.pdok.nl/bzk/locatieserver/search/v3_1/free?"
end
def valid_response?(response)
json = parse_json(response.body)
super(response) if json
end
def results(query)
return [] unless doc = fetch_data(query)
return doc['response']['docs']
end
def query_url_params(query)
{
fl: '*',
q: query.text,
wt: 'json'
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/tencent.rb | lib/geocoder/lookups/tencent.rb | require 'geocoder/lookups/base'
require "geocoder/results/tencent"
module Geocoder::Lookup
class Tencent < Base
def name
"Tencent"
end
def required_api_key_parts
["key"]
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://apis.map.qq.com/ws/geocoder/v1/?"
end
def content_key
'result'
end
def results(query, reverse = false)
return [] unless doc = fetch_data(query)
case doc['status']
when 0
return [doc[content_key]]
when 311
raise_error(Geocoder::InvalidApiKey, "invalid api key") ||
Geocoder.log(:warn, "#{name} Geocoding API error: invalid api key.")
when 310
raise_error(Geocoder::InvalidRequest, "invalid request.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: invalid request, invalid parameters.")
when 306
raise_error(Geocoder::InvalidRequest, "invalid request.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: invalid request, check response for more info.")
when 110
raise_error(Geocoder::RequestDenied, "request denied.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: request source is not authorized.")
end
return []
end
def query_url_params(query)
{
(query.reverse_geocode? ? :location : :address) => query.sanitized_text,
:key => configuration.api_key,
:output => "json"
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/pc_miler.rb | lib/geocoder/lookups/pc_miler.rb | require 'geocoder/lookups/base'
require "geocoder/results/pc_miler"
require 'cgi' unless defined?(CGI) && defined?(CGI.escape)
module Geocoder::Lookup
class PcMiler < Base
# https://developer.trimblemaps.com/restful-apis/location/single-search/single-search-api/#test-the-api-now
def valid_region_codes
# AF: Africa
# AS: Asia
# EU: Europe
# ME: Middle East
# MX: Mexico
# NA: North America
# OC: Oceania
# SA: South America
%w[AF AS EU ME MX NA OC SA]
end
def name
"PCMiler"
end
private # ---------------------------------------------------------------
def base_query_url(query)
region_code = region(query)
if !valid_region_codes.include?(region_code)
raise "region_code '#{region_code}' is invalid. use one of #{valid_region_codes}." \
"https://developer.trimblemaps.com/restful-apis/location/single-search/single-search-api/#test-the-api-now"
end
"#{protocol}://singlesearch.alk.com/#{region_code}/api/search?"
end
def results(query)
return [] unless data = fetch_data(query)
if data['Locations']
add_metadata_to_locations!(data)
data['Locations']
else
[]
end
end
def add_metadata_to_locations!(data)
confidence = data['QueryConfidence']
data['Locations'].each do |location|
location['QueryConfidence'] = confidence
end
end
def query_url_params(query)
if query.reverse_geocode?
lat,lon = query.coordinates
formatted_query = "#{CGI.escape(lat)},#{CGI.escape(lon)}"
else
formatted_query = query.text.to_s
end
{
authToken: configuration.api_key,
query: formatted_query,
# to add additional metadata to response such as QueryConfidence
include: 'Meta'
}.merge(super(query))
end
def region(query)
query.options[:region] || query.options['region'] || configuration[:region] || "NA"
end
def check_response_for_errors!(response)
if response.code.to_i == 403
raise_error(Geocoder::RequestDenied) ||
Geocoder.log(:warn, "Geocoding API error: 403 API key does not exist")
else
super(response)
end
end
def supported_protocols
[:https]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/google.rb | lib/geocoder/lookups/google.rb | require 'geocoder/lookups/base'
require "geocoder/results/google"
module Geocoder::Lookup
class Google < Base
def name
"Google"
end
def map_link_url(coordinates)
"http://maps.google.com/maps?q=#{coordinates.join(',')}"
end
def supported_protocols
# Google requires HTTPS if an API key is used.
if configuration.api_key
[:https]
else
[:http, :https]
end
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://maps.googleapis.com/maps/api/geocode/json?"
end
def configure_ssl!(client)
client.instance_eval {
@ssl_context = OpenSSL::SSL::SSLContext.new
options = OpenSSL::SSL::OP_NO_SSLv2 | OpenSSL::SSL::OP_NO_SSLv3
if OpenSSL::SSL.const_defined?('OP_NO_COMPRESSION')
options |= OpenSSL::SSL::OP_NO_COMPRESSION
end
@ssl_context.set_params({options: options})
}
end
def valid_response?(response)
json = parse_json(response.body)
status = json["status"] if json
super(response) and ['OK', 'ZERO_RESULTS'].include?(status)
end
def result_root_attr
'results'
end
def results(query)
return [] unless doc = fetch_data(query)
case doc['status']
when "OK" # OK status implies >0 results
return doc[result_root_attr]
when "OVER_QUERY_LIMIT"
raise_error(Geocoder::OverQueryLimitError) ||
Geocoder.log(:warn, "#{name} API error: over query limit.")
when "REQUEST_DENIED"
raise_error(Geocoder::RequestDenied, doc['error_message']) ||
Geocoder.log(:warn, "#{name} API error: request denied (#{doc['error_message']}).")
when "INVALID_REQUEST"
raise_error(Geocoder::InvalidRequest, doc['error_message']) ||
Geocoder.log(:warn, "#{name} API error: invalid request (#{doc['error_message']}).")
end
return []
end
def query_url_google_params(query)
params = {
:sensor => "false",
:language => (query.language || configuration.language)
}
if query.options[:google_place_id]
params[:place_id] = query.sanitized_text
else
params[(query.reverse_geocode? ? :latlng : :address)] = query.sanitized_text
end
unless (bounds = query.options[:bounds]).nil?
params[:bounds] = bounds.map{ |point| "%f,%f" % point }.join('|')
end
unless (region = query.options[:region]).nil?
params[:region] = region
end
unless (components = query.options[:components]).nil?
params[:components] = components.is_a?(Array) ? components.join("|") : components
end
unless (result_type = query.options[:result_type]).nil?
params[:result_type] = result_type.is_a?(Array) ? result_type.join("|") : result_type
end
params
end
def query_url_params(query)
query_url_google_params(query).merge(
:key => configuration.api_key
).merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/db_ip_com.rb | lib/geocoder/lookups/db_ip_com.rb | require 'geocoder/lookups/base'
require 'geocoder/results/db_ip_com'
module Geocoder::Lookup
class DbIpCom < Base
def name
'DB-IP.com'
end
def supported_protocols
[:https, :http]
end
def required_api_key_parts
['api_key']
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.db-ip.com/v2/#{configuration.api_key}/#{query.sanitized_text}?"
end
##
# Same as query_url but without the api key.
#
def cache_key(query)
"#{protocol}://api.db-ip.com/v2/#{query.sanitized_text}?" + hash_to_query(cache_key_params(query))
end
def results(query)
return [] unless (doc = fetch_data(query))
case doc['error']
when 'maximum number of queries per day exceeded'
raise_error Geocoder::OverQueryLimitError ||
Geocoder.log(:warn, 'DB-API query limit exceeded.')
when 'invalid API key'
raise_error Geocoder::InvalidApiKey ||
Geocoder.log(:warn, 'Invalid DB-IP API key.')
when nil
[doc]
else
raise_error Geocoder::Error ||
Geocoder.log(:warn, "Request failed: #{doc['error']}")
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/google_places_details.rb | lib/geocoder/lookups/google_places_details.rb | require "geocoder/lookups/google"
require "geocoder/results/google_places_details"
module Geocoder
module Lookup
class GooglePlacesDetails < Google
def name
"Google Places Details"
end
def required_api_key_parts
["key"]
end
def supported_protocols
[:https]
end
private
def base_query_url(query)
"#{protocol}://maps.googleapis.com/maps/api/place/details/json?"
end
def result_root_attr
'result'
end
def results(query)
result = super(query)
return [result] unless result.is_a? Array
result
end
def fields(query)
if query.options.has_key?(:fields)
return format_fields(query.options[:fields])
end
if configuration.has_key?(:fields)
return format_fields(configuration[:fields])
end
nil # use Google Places defaults
end
def format_fields(*fields)
flattened = fields.flatten.compact
return if flattened.empty?
flattened.join(',')
end
def query_url_google_params(query)
{
placeid: query.text,
fields: fields(query),
language: query.language || configuration.language
}
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/google_places_search.rb | lib/geocoder/lookups/google_places_search.rb | require "geocoder/lookups/google"
require "geocoder/results/google_places_search"
module Geocoder
module Lookup
class GooglePlacesSearch < Google
def name
"Google Places Search"
end
def required_api_key_parts
["key"]
end
def supported_protocols
[:https]
end
private
def result_root_attr
'candidates'
end
def base_query_url(query)
"#{protocol}://maps.googleapis.com/maps/api/place/findplacefromtext/json?"
end
def query_url_google_params(query)
{
input: query.text,
inputtype: 'textquery',
fields: fields(query),
locationbias: locationbias(query),
language: query.language || configuration.language
}
end
def fields(query)
if query.options.has_key?(:fields)
return format_fields(query.options[:fields])
end
if configuration.has_key?(:fields)
return format_fields(configuration[:fields])
end
default_fields
end
def default_fields
basic = %w[business_status formatted_address geometry icon name
photos place_id plus_code types]
contact = %w[opening_hours]
atmosphere = %W[price_level rating user_ratings_total]
format_fields(basic, contact, atmosphere)
end
def format_fields(*fields)
flattened = fields.flatten.compact
return if flattened.empty?
flattened.join(',')
end
def locationbias(query)
if query.options.has_key?(:locationbias)
query.options[:locationbias]
else
configuration[:locationbias]
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/base.rb | lib/geocoder/lookups/base.rb | require 'net/http'
require 'net/https'
require 'uri'
unless defined?(ActiveSupport::JSON)
begin
require 'json'
rescue LoadError
raise LoadError, "Please install the 'json' or 'json_pure' gem to parse geocoder results."
end
end
module Geocoder
module Lookup
class Base
def initialize
@cache = nil
end
##
# Human-readable name of the geocoding API.
#
def name
fail
end
##
# Symbol which is used in configuration to refer to this Lookup.
#
def handle
str = self.class.to_s
str[str.rindex(':')+1..-1].gsub(/([a-z\d]+)([A-Z])/,'\1_\2').downcase.to_sym
end
##
# Query the geocoding API and return a Geocoder::Result object.
# Returns +nil+ on timeout or error.
#
# Takes a search string (eg: "Mississippi Coast Coliseumf, Biloxi, MS",
# "205.128.54.202") for geocoding, or coordinates (latitude, longitude)
# for reverse geocoding. Returns an array of <tt>Geocoder::Result</tt>s.
#
def search(query, options = {})
query = Geocoder::Query.new(query, options) unless query.is_a?(Geocoder::Query)
results(query).map{ |r|
result = result_class.new(r)
result.cache_hit = @cache_hit if cache
result
}
end
##
# Return the URL for a map of the given coordinates.
#
# Not necessarily implemented by all subclasses as only some lookups
# also provide maps.
#
def map_link_url(coordinates)
nil
end
##
# Array containing string descriptions of keys required by the API.
# Empty array if keys are optional or not required.
#
def required_api_key_parts
[]
end
##
# URL to use for querying the geocoding engine.
#
# Subclasses should not modify this method. Instead they should define
# base_query_url and url_query_string. If absolutely necessary to
# subclss this method, they must also subclass #cache_key.
#
def query_url(query)
base_query_url(query) + url_query_string(query)
end
##
# The working Cache object.
#
def cache
if @cache.nil? and store = configuration.cache
cache_options = configuration.cache_options
@cache = Cache.new(store, cache_options)
end
@cache
end
##
# Array containing the protocols supported by the api.
# Should be set to [:http] if only HTTP is supported
# or [:https] if only HTTPS is supported.
#
def supported_protocols
[:http, :https]
end
private # -------------------------------------------------------------
##
# String which, when concatenated with url_query_string(query)
# produces the full query URL. Should include the "?" a the end.
#
def base_query_url(query)
fail
end
##
# An object with configuration data for this particular lookup.
#
def configuration
Geocoder.config_for_lookup(handle)
end
##
# Object used to make HTTP requests.
#
def http_client
proxy_name = "#{protocol}_proxy"
if proxy = configuration.send(proxy_name)
proxy_url = !!(proxy =~ /^#{protocol}/) ? proxy : protocol + '://' + proxy
begin
uri = URI.parse(proxy_url)
rescue URI::InvalidURIError
raise ConfigurationError,
"Error parsing #{protocol.upcase} proxy URL: '#{proxy_url}'"
end
Net::HTTP::Proxy(uri.host, uri.port, uri.user, uri.password)
else
Net::HTTP
end
end
##
# Geocoder::Result object or nil on timeout or other error.
#
def results(query)
fail
end
def query_url_params(query)
query.options[:params] || {}
end
def url_query_string(query)
hash_to_query(
query_url_params(query).reject{ |key,value| value.nil? }
)
end
##
# Key to use for caching a geocoding result. Usually this will be the
# request URL, but in cases where OAuth is used and the nonce,
# timestamp, etc varies from one request to another, we need to use
# something else (like the URL before OAuth encoding).
#
def cache_key(query)
base_query_url(query) + hash_to_query(cache_key_params(query))
end
def cache_key_params(query)
# omit api_key and token because they may vary among requests
query_url_params(query).reject do |key,value|
key.to_s.match(/(key|token)/)
end
end
##
# Class of the result objects
#
def result_class
Geocoder::Result.const_get(self.class.to_s.split(":").last)
end
##
# Raise exception if configuration specifies it should be raised.
# Return false if exception not raised.
#
def raise_error(error, message = nil)
exceptions = configuration.always_raise
if exceptions == :all or exceptions.include?( error.is_a?(Class) ? error : error.class )
raise error, message
else
false
end
end
##
# Returns a parsed search result (Ruby hash).
#
def fetch_data(query)
parse_raw_data fetch_raw_data(query)
rescue SocketError => err
raise_error(err) or Geocoder.log(:warn, "Geocoding API connection cannot be established.")
rescue Errno::ECONNREFUSED => err
raise_error(err) or Geocoder.log(:warn, "Geocoding API connection refused.")
rescue Geocoder::NetworkError => err
raise_error(err) or Geocoder.log(:warn, "Geocoding API connection is either unreacheable or reset by the peer")
rescue Timeout::Error => err
raise_error(err) or Geocoder.log(:warn, "Geocoding API not responding fast enough " +
"(use Geocoder.configure(:timeout => ...) to set limit).")
end
def parse_json(data)
if defined?(ActiveSupport::JSON)
ActiveSupport::JSON.decode(data)
else
JSON.parse(data)
end
rescue
unless raise_error(ResponseParseError.new(data))
Geocoder.log(:warn, "Geocoding API's response was not valid JSON")
Geocoder.log(:debug, "Raw response: #{data}")
end
end
##
# Parses a raw search result (returns hash or array).
#
def parse_raw_data(raw_data)
parse_json(raw_data)
end
##
# Protocol to use for communication with geocoding services.
# Set in configuration but not available for every service.
#
def protocol
"http" + (use_ssl? ? "s" : "")
end
def valid_response?(response)
(200..399).include?(response.code.to_i)
end
##
# Fetch a raw geocoding result (JSON string).
# The result might or might not be cached.
#
def fetch_raw_data(query)
key = cache_key(query)
if cache and body = cache[key]
@cache_hit = true
else
check_api_key_configuration!(query)
response = make_api_request(query)
check_response_for_errors!(response)
body = response.body
# apply the charset from the Content-Type header, if possible
ct = response['content-type']
if ct && ct['charset']
charset = ct.split(';').select do |s|
s['charset']
end.first.to_s.split('=')
if charset.length == 2
body.force_encoding(charset.last) rescue ArgumentError
end
end
if cache and valid_response?(response)
cache[key] = body
end
@cache_hit = false
end
body
end
def check_response_for_errors!(response)
if response.code.to_i == 400
raise_error(Geocoder::InvalidRequest) ||
Geocoder.log(:warn, "Geocoding API error: 400 Bad Request")
elsif response.code.to_i == 401
raise_error(Geocoder::RequestDenied) ||
Geocoder.log(:warn, "Geocoding API error: 401 Unauthorized")
elsif response.code.to_i == 402
raise_error(Geocoder::OverQueryLimitError) ||
Geocoder.log(:warn, "Geocoding API error: 402 Payment Required")
elsif response.code.to_i == 429
raise_error(Geocoder::OverQueryLimitError) ||
Geocoder.log(:warn, "Geocoding API error: 429 Too Many Requests")
elsif response.code.to_i == 503
raise_error(Geocoder::ServiceUnavailable) ||
Geocoder.log(:warn, "Geocoding API error: 503 Service Unavailable")
end
end
##
# Make an HTTP(S) request to a geocoding API and
# return the response object.
#
def make_api_request(query)
uri = URI.parse(query_url(query))
Geocoder.log(:debug, "Geocoder: HTTP request being made for #{uri.to_s}")
http_client.start(uri.host, uri.port, use_ssl: use_ssl?, open_timeout: configuration.timeout, read_timeout: configuration.timeout) do |client|
configure_ssl!(client) if use_ssl?
req = Net::HTTP::Get.new(uri.request_uri, configuration.http_headers)
if configuration.basic_auth[:user] and configuration.basic_auth[:password]
req.basic_auth(
configuration.basic_auth[:user],
configuration.basic_auth[:password]
)
end
client.request(req)
end
rescue Timeout::Error
raise Geocoder::LookupTimeout
rescue Errno::EHOSTUNREACH, Errno::ETIMEDOUT, Errno::ENETUNREACH, Errno::ECONNRESET
raise Geocoder::NetworkError
end
def use_ssl?
if supported_protocols == [:https]
true
elsif supported_protocols == [:http]
false
else
configuration.use_https
end
end
def configure_ssl!(client); end
def check_api_key_configuration!(query)
key_parts = query.lookup.required_api_key_parts
if key_parts.size > Array(configuration.api_key).size
parts_string = key_parts.size == 1 ? key_parts.first : key_parts
raise Geocoder::ConfigurationError,
"The #{query.lookup.name} API requires a key to be configured: " +
parts_string.inspect
end
end
##
# Simulate ActiveSupport's Object#to_query.
# Removes any keys with nil value.
#
def hash_to_query(hash)
require 'cgi' unless defined?(CGI) && defined?(CGI.escape)
hash.collect{ |p|
p[1].nil? ? nil : p.map{ |i| CGI.escape i.to_s } * '='
}.compact.sort * '&'
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/geoapify.rb | lib/geocoder/lookups/geoapify.rb | # frozen_string_literal: true
require 'geocoder/lookups/base'
require 'geocoder/results/geoapify'
module Geocoder
module Lookup
# https://apidocs.geoapify.com/docs/geocoding/api
class Geoapify < Base
def name
'Geoapify'
end
def required_api_key_parts
['api_key']
end
def supported_protocols
[:https]
end
private
def base_query_url(query)
method = if query.reverse_geocode?
'reverse'
elsif query.options[:autocomplete]
'autocomplete'
else
'search'
end
"https://api.geoapify.com/v1/geocode/#{method}?"
end
def results(query)
return [] unless (doc = fetch_data(query))
# The rest of the status codes should be already handled by the default
# functionality as the API returns correct HTTP response codes in most
# cases. There may be some unhandled cases still (such as over query
# limit reached) but there is not enough documentation to cover them.
case doc['statusCode']
when 500
raise_error(Geocoder::InvalidRequest) || Geocoder.log(:warn, doc['message'])
end
return [] unless doc['type'] == 'FeatureCollection'
return [] unless doc['features'] || doc['features'].present?
doc['features']
end
def query_url_params(query)
lang = query.language || configuration.language
params = { apiKey: configuration.api_key, lang: lang, limit: query.options[:limit] }
if query.reverse_geocode?
params.merge!(query_url_params_reverse(query))
else
params.merge!(query_url_params_coordinates(query))
end
params.merge!(super)
end
def query_url_params_coordinates(query)
{ text: query.sanitized_text }
end
def query_url_params_reverse(query)
{
lat: query.coordinates[0],
lon: query.coordinates[1]
}
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/nationaal_georegister_nl.rb | lib/geocoder/lookups/nationaal_georegister_nl.rb | require 'geocoder/lookups/base'
require "geocoder/results/nationaal_georegister_nl"
module Geocoder::Lookup
class NationaalGeoregisterNl < Base
def name
'Nationaal Georegister Nederland'
end
private # ---------------------------------------------------------------
def cache_key(query)
base_query_url(query) + hash_to_query(query_url_params(query))
end
def base_query_url(query)
"#{protocol}://geodata.nationaalgeoregister.nl/locatieserver/v3/free?"
end
def valid_response?(response)
json = parse_json(response.body)
super(response) if json
end
def results(query)
return [] unless doc = fetch_data(query)
return doc['response']['docs']
end
def query_url_params(query)
{
fl: '*',
q: query.text
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/azure.rb | lib/geocoder/lookups/azure.rb | require 'geocoder/lookups/base'
require 'geocoder/results/azure'
module Geocoder::Lookup
class Azure < Base
def name
'Azure'
end
def required_api_key_parts
['api_key']
end
def supported_protocols
[:https]
end
private
def base_query_url(query)
host = 'atlas.microsoft.com/search/address'
if query.reverse_geocode?
"#{protocol}://#{host}/reverse/json?"
else
"#{protocol}://#{host}/json?"
end
end
def query_url_params(query)
params = {
'api-version' => 1.0,
'language' => query.options[:language] || 'en',
'limit' => configuration[:limit] || 10,
'query' => query.sanitized_text,
'subscription-key' => configuration.api_key
}
params.merge(super)
end
def results(query)
return [] unless (doc = fetch_data(query))
return doc if doc['error']
if doc['results']&.any?
doc['results']
elsif doc['addresses']&.any?
doc['addresses']
else
[]
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/baidu.rb | lib/geocoder/lookups/baidu.rb | require 'geocoder/lookups/base'
require "geocoder/results/baidu"
module Geocoder::Lookup
class Baidu < Base
def name
"Baidu"
end
def required_api_key_parts
["key"]
end
# HTTP only
def supported_protocols
[:http]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.map.baidu.com/geocoder/v2/?"
end
def content_key
'result'
end
def results(query, reverse = false)
return [] unless doc = fetch_data(query)
case doc['status']
when 0
return [doc[content_key]] unless doc[content_key].blank?
when 1, 3, 4
raise_error(Geocoder::Error, "server error.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: server error.")
when 2
raise_error(Geocoder::InvalidRequest, "invalid request.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: invalid request.")
when 5
raise_error(Geocoder::InvalidApiKey, "invalid api key") ||
Geocoder.log(:warn, "#{name} Geocoding API error: invalid api key.")
when 101, 102, 200..299
raise_error(Geocoder::RequestDenied, "request denied") ||
Geocoder.log(:warn, "#{name} Geocoding API error: request denied.")
when 300..399
raise_error(Geocoder::OverQueryLimitError, "over query limit.") ||
Geocoder.log(:warn, "#{name} Geocoding API error: over query limit.")
end
return []
end
def query_url_params(query)
{
(query.reverse_geocode? ? :location : :address) => query.sanitized_text,
:ak => configuration.api_key,
:output => "json"
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/opencagedata.rb | lib/geocoder/lookups/opencagedata.rb | require 'geocoder/lookups/base'
require 'geocoder/results/opencagedata'
module Geocoder::Lookup
class Opencagedata < Base
def name
"OpenCageData"
end
def required_api_key_parts
["key"]
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.opencagedata.com/geocode/v1/json?"
end
def results(query)
return [] unless doc = fetch_data(query)
# return doc["results"]
messages = doc['status']['message']
case doc['status']['code']
when 400 # Error with input
raise_error(Geocoder::InvalidRequest, messages) ||
Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
when 403 # Key related error
raise_error(Geocoder::InvalidApiKey, messages) ||
Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
when 402 # Quata Exceeded
raise_error(Geocoder::OverQueryLimitError, messages) ||
Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
when 500 # Unknown error
raise_error(Geocoder::Error, messages) ||
Geocoder.log(:warn, "Opencagedata Geocoding API error: #{messages}")
end
return doc["results"]
end
def query_url_params(query)
params = {
:q => query.sanitized_text,
:key => configuration.api_key,
:language => (query.language || configuration.language)
}.merge(super)
[:abbrv, :countrycode, :min_confidence, :no_dedupe, :no_annotations, :no_record, :limit].each do |option|
unless (option_value = query.options[option]).nil?
params[option] = option_value
end
end
unless (bounds = query.options[:bounds]).nil?
params[:bounds] = bounds.map{ |point| "%f,%f" % point }.join(',')
end
params
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/freegeoip.rb | lib/geocoder/lookups/freegeoip.rb | require 'geocoder/lookups/base'
require 'geocoder/results/freegeoip'
module Geocoder::Lookup
class Freegeoip < Base
def name
"FreeGeoIP"
end
def supported_protocols
if configuration[:host]
[:https]
else
# use https for default host
[:https]
end
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://#{host}/json/#{query.sanitized_text}?"
end
def query_url_params(query)
{
:apikey => configuration.api_key
}.merge(super)
end
def parse_raw_data(raw_data)
raw_data.match(/^<html><title>404/) ? nil : super(raw_data)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
# note: Freegeoip.net returns plain text "Not Found" on bad request
(doc = fetch_data(query)) ? [doc] : []
end
def reserved_result(ip)
{
"ip" => ip,
"city" => "",
"region_code" => "",
"region_name" => "",
"metro_code" => "",
"zip_code" => "",
"latitude" => "0",
"longitude" => "0",
"country_name" => "Reserved",
"country_code" => "RD"
}
end
def host
configuration[:host] || "freegeoip.app"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/pickpoint.rb | lib/geocoder/lookups/pickpoint.rb | require "geocoder/lookups/nominatim"
require "geocoder/results/pickpoint"
module Geocoder::Lookup
class Pickpoint < Nominatim
def name
"Pickpoint"
end
def supported_protocols
[:https]
end
def required_api_key_parts
["api_key"]
end
private # ----------------------------------------------------------------
def base_query_url(query)
method = query.reverse_geocode? ? "reverse" : "forward"
"#{protocol}://api.pickpoint.io/v1/#{method}?"
end
def query_url_params(query)
{
key: configuration.api_key
}.merge(super)
end
def results(query)
return [] unless doc = fetch_data(query)
if !doc.is_a?(Array) && doc['message'] == 'Unauthorized'
raise_error(Geocoder::InvalidApiKey, 'Unauthorized')
end
doc.is_a?(Array) ? doc : [doc]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipinfo_io_lite.rb | lib/geocoder/lookups/ipinfo_io_lite.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipinfo_io_lite'
module Geocoder::Lookup
class IpinfoIoLite < Base
def name
'Ipinfo.io Lite'
end
private # ---------------------------------------------------------------
def base_query_url(query)
url = "#{protocol}://api.ipinfo.io/lite/#{query.sanitized_text}"
url << '?' if configuration.api_key
url
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
if !(doc = fetch_data(query)).is_a?(Hash) or doc['error']
[]
else
[doc]
end
end
def reserved_result(ip)
{
'ip' => ip,
'bogon' => true
}
end
def query_url_params(query)
{
token: configuration.api_key
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ip2location.rb | lib/geocoder/lookups/ip2location.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ip2location'
module Geocoder::Lookup
class Ip2location < Base
def name
"IP2LocationApi"
end
def required_api_key_parts
['key']
end
def supported_protocols
[:http, :https]
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.ip2location.com/v2/?"
end
def query_url_params(query)
super.merge(
key: configuration.api_key,
ip: query.sanitized_text,
package: configuration[:package],
)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
return [] unless doc = fetch_data(query)
if doc["response"] == "INVALID ACCOUNT"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "INVALID ACCOUNT")
return []
else
return [doc]
end
end
def reserved_result(query)
{
"country_code" => "INVALID IP ADDRESS",
"country_name" => "INVALID IP ADDRESS",
"region_name" => "INVALID IP ADDRESS",
"city_name" => "INVALID IP ADDRESS",
"latitude" => "INVALID IP ADDRESS",
"longitude" => "INVALID IP ADDRESS",
"zip_code" => "INVALID IP ADDRESS",
"time_zone" => "INVALID IP ADDRESS",
"isp" => "INVALID IP ADDRESS",
"domain" => "INVALID IP ADDRESS",
"net_speed" => "INVALID IP ADDRESS",
"idd_code" => "INVALID IP ADDRESS",
"area_code" => "INVALID IP ADDRESS",
"weather_station_code" => "INVALID IP ADDRESS",
"weather_station_name" => "INVALID IP ADDRESS",
"mcc" => "INVALID IP ADDRESS",
"mnc" => "INVALID IP ADDRESS",
"mobile_brand" => "INVALID IP ADDRESS",
"elevation" => "INVALID IP ADDRESS",
"usage_type" => "INVALID IP ADDRESS"
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/mapbox.rb | lib/geocoder/lookups/mapbox.rb | require 'geocoder/lookups/base'
require "geocoder/results/mapbox"
module Geocoder::Lookup
class Mapbox < Base
def name
"Mapbox"
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.mapbox.com/geocoding/v5/#{dataset}/#{mapbox_search_term(query)}.json?"
end
def results(query)
return [] unless data = fetch_data(query)
if data['features']
sort_relevant_feature(data['features'])
elsif data['message'] =~ /Invalid\sToken/
raise_error(Geocoder::InvalidApiKey, data['message'])
[]
else
[]
end
end
def query_url_params(query)
{access_token: configuration.api_key}.merge(super(query))
end
def mapbox_search_term(query)
require 'erb' unless defined?(ERB) && defined?(ERB::Util.url_encode)
if query.reverse_geocode?
lat,lon = query.coordinates
"#{ERB::Util.url_encode lon},#{ERB::Util.url_encode lat}"
else
# truncate at first semicolon so Mapbox doesn't go into batch mode
# (see Github issue #1299)
ERB::Util.url_encode query.text.to_s.split(';').first.to_s
end
end
def dataset
configuration[:dataset] || "mapbox.places"
end
def supported_protocols
[:https]
end
def sort_relevant_feature(features)
# Sort by descending relevance; Favor original order for equal relevance (eg occurs for reverse geocoding)
features.sort_by do |feature|
[feature["relevance"],-features.index(feature)]
end.reverse
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ip2location_io.rb | lib/geocoder/lookups/ip2location_io.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ip2location_io'
module Geocoder::Lookup
class Ip2locationIo < Base
def name
"IP2LocationIOApi"
end
def required_api_key_parts
['key']
end
def supported_protocols
[:http, :https]
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.ip2location.io/?"
end
def query_url_params(query)
super.merge(
key: configuration.api_key,
ip: query.sanitized_text,
)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
return [] unless doc = fetch_data(query)
if doc["response"] == "INVALID ACCOUNT"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "INVALID ACCOUNT")
return []
else
return [doc]
end
end
def reserved_result(query)
{
"ip" => "-",
"country_code" => "-",
"country_name" => "-",
"region_name" => "-",
"city_name" => "-",
"latitude" => nil,
"longitude" => nil,
"zip_code" => "-",
"time_zone" => "-",
"asn" => "-",
"as" => "-",
"is_proxy" => false
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/amap.rb | lib/geocoder/lookups/amap.rb | require 'geocoder/lookups/base'
require "geocoder/results/amap"
module Geocoder::Lookup
class Amap < Base
def name
"AMap"
end
def required_api_key_parts
["key"]
end
def supported_protocols
[:http]
end
private # ---------------------------------------------------------------
def base_query_url(query)
path = query.reverse_geocode? ? 'regeo' : 'geo'
"http://restapi.amap.com/v3/geocode/#{path}?"
end
def results(query, reverse = false)
return [] unless doc = fetch_data(query)
case [doc['status'], doc['info']]
when ['1', 'OK']
return doc['regeocodes'] unless doc['regeocodes'].blank?
return [doc['regeocode']] unless doc['regeocode'].blank?
return doc['geocodes'] unless doc['geocodes'].blank?
when ['0', 'INVALID_USER_KEY']
raise_error(Geocoder::InvalidApiKey, "invalid api key") ||
Geocoder.log(:warn, "#{self.name} Geocoding API error: invalid api key.")
else
raise_error(Geocoder::Error, "server error.") ||
Geocoder.log(:warn, "#{self.name} Geocoding API error: server error - [#{doc['info']}]")
end
return []
end
def query_url_params(query)
params = {
:key => configuration.api_key,
:output => "json"
}
if query.reverse_geocode?
params[:location] = revert_coordinates(query.text)
params[:extensions] = "all"
params[:coordsys] = "gps"
else
params[:address] = query.sanitized_text
end
params.merge(super)
end
def revert_coordinates(text)
[text[1],text[0]].join(",")
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/melissa_street.rb | lib/geocoder/lookups/melissa_street.rb | require 'geocoder/lookups/base'
require "geocoder/results/melissa_street"
module Geocoder::Lookup
class MelissaStreet < Base
def name
"MelissaStreet"
end
def results(query)
return [] unless doc = fetch_data(query)
if doc["TransmissionResults"] == "GE05"
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "Melissa service error: invalid API key.")
end
return doc["Records"]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://address.melissadata.net/v3/WEB/GlobalAddress/doGlobalAddress?"
end
def query_url_params(query)
params = {
id: configuration.api_key,
format: "JSON",
a1: query.sanitized_text,
loc: query.options[:city],
admarea: query.options[:state],
postal: query.options[:postal],
ctry: query.options[:country]
}
params.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/maxmind_geoip2.rb | lib/geocoder/lookups/maxmind_geoip2.rb | require 'geocoder/lookups/base'
require 'geocoder/results/maxmind_geoip2'
module Geocoder::Lookup
class MaxmindGeoip2 < Base
def name
"MaxMind GeoIP2"
end
# Maxmind's GeoIP2 Precision Services only supports HTTPS,
# otherwise a `404 Not Found` HTTP response will be returned
def supported_protocols
[:https]
end
def query_url(query)
"#{protocol}://geoip.maxmind.com/geoip/v2.1/#{configured_service!}/#{query.sanitized_text.strip}"
end
private # ---------------------------------------------------------------
def cache_key(query)
query_url(query)
end
##
# Return the name of the configured service, or raise an exception.
#
def configured_service!
if s = configuration[:service] and services.include?(s) and configuration[:basic_auth][:user] and configuration[:basic_auth][:password]
return s
else
raise(
Geocoder::ConfigurationError, "When using MaxMind GeoIP2 you must specify a service and credentials: Geocoder.configure(maxmind_geoip2: {service: ..., basic_auth: {user: ..., password: ...}}), where service is one of: #{services.inspect}"
)
end
end
def data_contains_error?(doc)
(["code", "error"] - doc.keys).empty?
end
##
# Service names used in URL.
#
def services
[
:country,
:city,
:insights,
]
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [] if query.internal_ip_address?
doc = fetch_data(query)
if doc
if !data_contains_error?(doc)
return [doc]
else
Geocoder.log(:warn, "MaxMind GeoIP2 Geocoding API error: #{doc['code']} (#{doc['error']}).")
end
end
return []
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/postcode_anywhere_uk.rb | lib/geocoder/lookups/postcode_anywhere_uk.rb | require 'geocoder/lookups/base'
require 'geocoder/results/postcode_anywhere_uk'
module Geocoder::Lookup
class PostcodeAnywhereUk < Base
# API documentation: http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/
DAILY_LIMIT_EXEEDED_ERROR_CODES = ['8', '17'] # api docs say these two codes are the same error
INVALID_API_KEY_ERROR_CODE = '2'
def name
'PostcodeAnywhereUk'
end
def required_api_key_parts
%w(key)
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://services.postcodeanywhere.co.uk/Geocoding/UK/Geocode/v2.00/json.ws?"
end
def results(query)
response = fetch_data(query)
return [] if response.nil? || !response.is_a?(Array) || response.empty?
raise_exception_for_response(response[0]) if response[0]['Error']
response
end
def raise_exception_for_response(response)
case response['Error']
when *DAILY_LIMIT_EXEEDED_ERROR_CODES
raise_error(Geocoder::OverQueryLimitError, response['Cause']) || Geocoder.log(:warn, response['Cause'])
when INVALID_API_KEY_ERROR_CODE
raise_error(Geocoder::InvalidApiKey, response['Cause']) || Geocoder.log(:warn, response['Cause'])
else # anything else just raise general error with the api cause
raise_error(Geocoder::Error, response['Cause']) || Geocoder.log(:warn, response['Cause'])
end
end
def query_url_params(query)
{
:location => query.sanitized_text,
:key => configuration.api_key
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/postcodes_io.rb | lib/geocoder/lookups/postcodes_io.rb | require 'geocoder/lookups/base'
require 'geocoder/results/postcodes_io'
module Geocoder::Lookup
class PostcodesIo < Base
def name
'Postcodes.io'
end
def query_url(query)
"#{protocol}://api.postcodes.io/postcodes/#{query.sanitized_text.gsub(/\s/, '')}"
end
def supported_protocols
[:https]
end
private # ----------------------------------------------------------------
def cache_key(query)
query_url(query)
end
def results(query)
response = fetch_data(query)
return [] if response.nil? || response['status'] != 200 || response.empty?
[response['result']]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/here.rb | lib/geocoder/lookups/here.rb | require 'geocoder/lookups/base'
require 'geocoder/results/here'
module Geocoder::Lookup
class Here < Base
def name
"Here"
end
def required_api_key_parts
['api_key']
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
service = query.reverse_geocode? ? "revgeocode" : "geocode"
"#{protocol}://#{service}.search.hereapi.com/v1/#{service}?"
end
def results(query)
unless configuration.api_key.is_a?(String)
api_key_not_string!
return []
end
return [] unless doc = fetch_data(query)
return [] if doc["items"].nil?
doc["items"]
end
def query_url_here_options(query, reverse_geocode)
options = {
apiKey: configuration.api_key,
lang: (query.language || configuration.language)
}
return options if reverse_geocode
unless (country = query.options[:country]).nil?
options[:in] = "countryCode:#{country}"
end
options
end
def query_url_params(query)
if query.reverse_geocode?
super.merge(query_url_here_options(query, true)).merge(
at: query.sanitized_text
)
else
super.merge(query_url_here_options(query, false)).merge(
q: query.sanitized_text
)
end
end
def api_key_not_string!
msg = <<~MSG
API key for HERE Geocoding and Search API should be a string.
For more info on how to obtain it, please see https://developer.here.com/documentation/identity-access-management/dev_guide/topics/plat-using-apikeys.html
MSG
raise_error(Geocoder::ConfigurationError, msg) || Geocoder.log(:warn, msg)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/osmnames.rb | lib/geocoder/lookups/osmnames.rb | require 'cgi'
require 'geocoder/lookups/base'
require 'geocoder/results/osmnames'
module Geocoder::Lookup
class Osmnames < Base
def name
'OSM Names'
end
def required_api_key_parts
configuration[:host] ? [] : ['key']
end
def supported_protocols
[:https]
end
private
def base_query_url(query)
"#{base_url(query)}/#{params_url(query)}.js?"
end
def base_url(query)
host = configuration[:host] || 'geocoder.tilehosting.com'
"#{protocol}://#{host}"
end
def params_url(query)
method, args = 'q', CGI.escape(query.sanitized_text)
method, args = 'r', query.coordinates.join('/') if query.reverse_geocode?
"#{country_limited(query)}#{method}/#{args}"
end
def results(query)
return [] unless doc = fetch_data(query)
if (error = doc['message'])
raise_error(Geocoder::InvalidRequest, error) ||
Geocoder.log(:warn, "OSMNames Geocoding API error: #{error}")
else
return doc['results']
end
end
def query_url_params(query)
{
key: configuration.api_key
}.merge(super)
end
def country_limited(query)
"#{query.options[:country_code].downcase}/" if query.options[:country_code] && !query.reverse_geocode?
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipgeolocation.rb | lib/geocoder/lookups/ipgeolocation.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipgeolocation'
module Geocoder::Lookup
class Ipgeolocation < Base
ERROR_CODES = {
400 => Geocoder::RequestDenied, # subscription is paused
401 => Geocoder::InvalidApiKey, # missing/invalid API key
403 => Geocoder::InvalidRequest, # invalid IP address
404 => Geocoder::InvalidRequest, # not found
423 => Geocoder::InvalidRequest # bogon/reserved IP address
}
ERROR_CODES.default = Geocoder::Error
def name
"Ipgeolocation"
end
def supported_protocols
[:https]
end
private # ----------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.ipgeolocation.io/ipgeo?"
end
def query_url_params(query)
{
ip: query.sanitized_text,
apiKey: configuration.api_key
}.merge(super)
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
[fetch_data(query)]
end
def reserved_result(ip)
{
"ip" => ip,
"country_name" => "Reserved",
"country_code2" => "RD"
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/geoportail_lu.rb | lib/geocoder/lookups/geoportail_lu.rb | require 'geocoder/lookups/base'
require "geocoder/results/geoportail_lu"
module Geocoder
module Lookup
class GeoportailLu < Base
def name
"Geoportail.lu"
end
private # ---------------------------------------------------------------
def base_query_url(query)
if query.reverse_geocode?
reverse_geocode_url_base_path
else
search_url_base_path
end
end
def search_url_base_path
"#{protocol}://api.geoportail.lu/geocoder/search?"
end
def reverse_geocode_url_base_path
"#{protocol}://api.geoportail.lu/geocoder/reverseGeocode?"
end
def query_url_geoportail_lu_params(query)
query.reverse_geocode? ? reverse_geocode_params(query) : search_params(query)
end
def search_params(query)
{
queryString: query.sanitized_text
}
end
def reverse_geocode_params(query)
lat_lon = query.coordinates
{
lat: lat_lon.first,
lon: lat_lon.last
}
end
def query_url_params(query)
query_url_geoportail_lu_params(query).merge(super)
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['success'] == true
result = doc['results']
else
result = []
raise_error(Geocoder::Error) ||
Geocoder.log(:warn, "Geportail.lu Geocoding API error")
end
result
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/nominatim.rb | lib/geocoder/lookups/nominatim.rb | require 'geocoder/lookups/base'
require "geocoder/results/nominatim"
module Geocoder::Lookup
class Nominatim < Base
def name
"Nominatim"
end
def map_link_url(coordinates)
"https://www.openstreetmap.org/?lat=#{coordinates[0]}&lon=#{coordinates[1]}&zoom=15&layers=M"
end
private # ---------------------------------------------------------------
def supported_protocols
[:https]
end
def base_query_url(query)
method = query.reverse_geocode? ? "reverse" : "search"
"#{protocol}://#{configured_host}/#{method}?"
end
def configured_host
configuration[:host] || "nominatim.openstreetmap.org"
end
def use_ssl?
# nominatim.openstreetmap.org redirects HTTP requests to HTTPS
if configured_host == "nominatim.openstreetmap.org"
true
else
super
end
end
def results(query)
return [] unless doc = fetch_data(query)
doc.is_a?(Array) ? doc : [doc]
end
def parse_raw_data(raw_data)
if raw_data.include?("Bandwidth limit exceeded")
raise_error(Geocoder::OverQueryLimitError) || Geocoder.log(:warn, "Over API query limit.")
else
super(raw_data)
end
end
def query_url_params(query)
params = {
:format => "json",
:addressdetails => "1",
:"accept-language" => (query.language || configuration.language)
}.merge(super)
if query.reverse_geocode?
lat,lon = query.coordinates
params[:lat] = lat
params[:lon] = lon
else
params[:q] = query.sanitized_text
end
params
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/geoip2.rb | lib/geocoder/lookups/geoip2.rb | require 'geocoder/lookups/base'
require 'geocoder/results/geoip2'
module Geocoder
module Lookup
class Geoip2 < Base
attr_reader :gem_name
def initialize
unless configuration[:file].nil?
begin
@gem_name = configuration[:lib] || 'maxminddb'
require @gem_name
rescue LoadError
raise "Could not load Maxmind DB dependency. To use the GeoIP2 lookup you must add the #{@gem_name} gem to your Gemfile or have it installed in your system."
end
@mmdb = db_class.new(configuration[:file].to_s)
end
super
end
def name
'GeoIP2'
end
def required_api_key_parts
[]
end
private
def db_class
gem_name == 'hive_geoip2' ? Hive::GeoIP2 : MaxMindDB
end
def results(query)
return [] unless configuration[:file]
if @mmdb.respond_to?(:local_ip_alias) && !configuration[:local_ip_alias].nil?
@mmdb.local_ip_alias = configuration[:local_ip_alias]
end
result = @mmdb.lookup(query.to_s)
result.nil? ? [] : [result]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/pelias.rb | lib/geocoder/lookups/pelias.rb | require 'geocoder/lookups/base'
require 'geocoder/results/pelias'
module Geocoder::Lookup
class Pelias < Base
def name
'Pelias'
end
def endpoint
configuration[:endpoint] || 'localhost'
end
def required_api_key_parts
['search-XXXX']
end
private # ----------------------------------------------------------------
def base_query_url(query)
query_type = query.reverse_geocode? ? 'reverse' : 'search'
"#{protocol}://#{endpoint}/v1/#{query_type}?"
end
def query_url_params(query)
params = {
api_key: configuration.api_key
}.merge(super)
if query.reverse_geocode?
lat, lon = query.coordinates
params[:'point.lat'] = lat
params[:'point.lon'] = lon
else
params[:text] = query.text
end
params
end
def results(query)
return [] unless doc = fetch_data(query)
# not all responses include a meta
if doc['meta']
error = doc.fetch('results', {}).fetch('error', {})
message = error.fetch('type', 'Unknown Error') + ': ' + error.fetch('message', 'No message')
log_message = 'Pelias Geocoding API error - ' + message
case doc['meta']['status_code']
when '200'
# nothing to see here
when '403'
raise_error(Geocoder::RequestDenied, message) || Geocoder.log(:warn, log_message)
when '429'
raise_error(Geocoder::OverQueryLimitError, message) || Geocoder.log(:warn, log_message)
else
raise_error(Geocoder::Error, message) || Geocoder.log(:warn, log_message)
end
end
doc['features'] || []
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/yandex.rb | lib/geocoder/lookups/yandex.rb | require 'geocoder/lookups/base'
require "geocoder/results/yandex"
module Geocoder::Lookup
class Yandex < Base
def name
"Yandex"
end
def map_link_url(coordinates)
"http://maps.yandex.ru/?ll=#{coordinates.reverse.join(',')}"
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://geocode-maps.yandex.ru/1.x/?"
end
def results(query)
return [] unless doc = fetch_data(query)
if [400, 403].include? doc['statusCode']
if doc['statusCode'] == 403 and doc['message'] == 'Invalid key'
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "Invalid API key.")
else
Geocoder.log(:warn, "Yandex Geocoding API error: #{doc['statusCode']} (#{doc['message']}).")
end
return []
end
if doc = doc['response']['GeoObjectCollection']
return doc['featureMember'].to_a
else
Geocoder.log(:warn, "Yandex Geocoding API error: unexpected response format.")
return []
end
end
def query_url_params(query)
if query.reverse_geocode?
q = query.coordinates.reverse.join(",")
else
q = query.sanitized_text
end
params = {
:geocode => q,
:format => "json",
:lang => "#{query.language || configuration.language}", # supports ru, uk, be, default -> ru
:apikey => configuration.api_key
}
unless (bounds = query.options[:bounds]).nil?
params[:bbox] = bounds.map{ |point| "%f,%f" % point }.join('~')
end
params.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/twogis.rb | lib/geocoder/lookups/twogis.rb | require 'geocoder/lookups/base'
require "geocoder/results/twogis"
module Geocoder::Lookup
class Twogis < Base
def name
"2gis"
end
def required_api_key_parts
["key"]
end
def map_link_url(coordinates)
"https://2gis.ru/?m=#{coordinates.join(',')}"
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://catalog.api.2gis.com/3.0/items/geocode?"
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['meta'] && doc['meta']['error']
Geocoder.log(:warn, "2gis Geocoding API error: #{doc['meta']["code"]} (#{doc['meta']['error']["message"]}).")
return []
end
if doc['result'] && doc = doc['result']['items']
return doc.to_a
else
Geocoder.log(:warn, "2gis Geocoding API error: unexpected response format.")
return []
end
end
def query_url_params(query)
if query.reverse_geocode?
q = query.coordinates.reverse.join(",")
else
q = query.sanitized_text
end
params = {
:q => q,
:lang => "#{query.language || configuration.language}",
:key => configuration.api_key,
:fields => 'items.street,items.adm_div,items.full_address_name,items.point,items.geometry.centroid'
}
params.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/esri.rb | lib/geocoder/lookups/esri.rb | require 'geocoder/lookups/base'
require "geocoder/results/esri"
require 'geocoder/esri_token'
module Geocoder::Lookup
class Esri < Base
def name
"Esri"
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
action = query.reverse_geocode? ? "reverseGeocode" : "find"
"#{protocol}://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/#{action}?"
end
def results(query)
return [] unless doc = fetch_data(query)
if (doc['error'].nil?)
if (!query.reverse_geocode?)
return [] if !doc['locations'] || doc['locations'].empty?
end
return [ doc ]
else
case [ doc['error']['code'] ]
when [498]
raise_error(Geocoder::InvalidApiKey, doc['error']['message']) ||
Geocoder.log(:warn, "#{self.name} Geocoding API error: #{doc['error']['message']}")
when [ 403 ]
raise_error(Geocoder::RequestDenied, 'ESRI request denied') ||
Geocoder.log(:warn, "#{self.name} ESRI request denied: #{doc['error']['message']}")
when [ 500 ], [501]
raise_error(Geocoder::ServiceUnavailable, 'ESRI service unavailable') ||
Geocoder.log(:warn, "#{self.name} ESRI service error: #{doc['error']['message']}")
else
raise_error(Geocoder::Error, doc['error']['message']) ||
Geocoder.log(:warn, "#{self.name} Geocoding error: #{doc['error']['message']}")
end
end
return []
end
def query_url_params(query)
params = {
:f => "pjson",
:outFields => "*"
}
if query.reverse_geocode?
params[:location] = query.coordinates.reverse.join(',')
else
params[:text] = query.sanitized_text
end
params[:token] = token(query)
if for_storage_value = for_storage(query)
params[:forStorage] = for_storage_value
end
params[:sourceCountry] = configuration[:source_country] if configuration[:source_country]
params[:preferredLabelValues] = configuration[:preferred_label_values] if configuration[:preferred_label_values]
params.merge(super)
end
def for_storage(query)
if query.options.has_key?(:for_storage)
query.options[:for_storage]
else
configuration[:for_storage]
end
end
def token(query)
token_instance = if query.options[:token]
query.options[:token]
else
configuration[:token]
end
if !valid_token_configured?(token_instance) && configuration.api_key
token_instance = create_and_save_token!(query)
end
token_instance.to_s unless token_instance.nil?
end
def valid_token_configured?(token_instance)
!token_instance.nil? && token_instance.active?
end
def create_and_save_token!(query)
token_instance = create_token
if query.options[:token]
query.options[:token] = token_instance
else
Geocoder.merge_into_lookup_config(:esri, token: token_instance)
end
token_instance
end
def create_token
Geocoder::EsriToken.generate_token(*configuration.api_key)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/location_iq.rb | lib/geocoder/lookups/location_iq.rb | require 'geocoder/lookups/nominatim'
require "geocoder/results/location_iq"
module Geocoder::Lookup
class LocationIq < Nominatim
def name
"LocationIq"
end
def required_api_key_parts
["api_key"]
end
def supported_protocols
[:https]
end
private # ----------------------------------------------------------------
def base_query_url(query)
method = query.reverse_geocode? ? "reverse" : "search"
"#{protocol}://#{configured_host}/v1/#{method}.php?"
end
def query_url_params(query)
{
key: configuration.api_key
}.merge(super)
end
def configured_host
configuration[:host] || "us1.locationiq.com"
end
def results(query)
return [] unless doc = fetch_data(query)
if !doc.is_a?(Array)
case doc['error']
when "Invalid key"
raise_error(Geocoder::InvalidApiKey, doc['error'])
when "Key not active - Please write to contact@unwiredlabs.com"
raise_error(Geocoder::RequestDenied, doc['error'])
when "Rate Limited"
raise_error(Geocoder::OverQueryLimitError, doc['error'])
when "Unknown error - Please try again after some time"
raise_error(Geocoder::InvalidRequest, doc['error'])
end
end
doc.is_a?(Array) ? doc : [doc]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipbase.rb | lib/geocoder/lookups/ipbase.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipbase'
module Geocoder::Lookup
class Ipbase < Base
def name
"ipbase.com"
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"https://api.ipbase.com/v2/info?"
end
def query_url_params(query)
{
:ip => query.sanitized_text,
:apikey => configuration.api_key
}
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
doc = fetch_data(query) || {}
doc.fetch("data", {})["location"] ? [doc] : []
end
def reserved_result(ip)
{
"data" => {
"ip" => ip,
"location" => {
"city" => { "name" => "" },
"country" => { "alpha2" => "RD", "name" => "Reserved" },
"region" => { "alpha2" => "", "name" => "" },
"zip" => ""
}
}
}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/maxmind_local.rb | lib/geocoder/lookups/maxmind_local.rb | require 'ipaddr'
require 'geocoder/lookups/base'
require 'geocoder/results/maxmind_local'
module Geocoder::Lookup
class MaxmindLocal < Base
def initialize
if !configuration[:file].nil?
begin
gem = RUBY_PLATFORM == 'java' ? 'jgeoip' : 'geoip'
require gem
rescue LoadError
raise "Could not load geoip dependency. To use MaxMind Local lookup you must add the #{gem} gem to your Gemfile or have it installed in your system."
end
end
super
end
def name
"MaxMind Local"
end
def required_api_key_parts
[]
end
private
def results(query)
if configuration[:file]
geoip_class = RUBY_PLATFORM == "java" ? JGeoIP : GeoIP
geoip_instance = geoip_class.new(configuration[:file])
result =
if configuration[:package] == :country
geoip_instance.country(query.to_s)
else
geoip_instance.city(query.to_s)
end
result.nil? ? [] : [encode_hash(result.to_hash)]
elsif configuration[:package] == :city
addr = IPAddr.new(query.text).to_i
q = "SELECT l.country, l.region, l.city, l.latitude, l.longitude
FROM maxmind_geolite_city_location l WHERE l.loc_id = (SELECT b.loc_id FROM maxmind_geolite_city_blocks b
WHERE b.start_ip_num <= #{addr} AND #{addr} <= b.end_ip_num)"
format_result(q, [:country_name, :region_name, :city_name, :latitude, :longitude])
elsif configuration[:package] == :country
addr = IPAddr.new(query.text).to_i
q = "SELECT country, country_code FROM maxmind_geolite_country
WHERE start_ip_num <= #{addr} AND #{addr} <= end_ip_num"
format_result(q, [:country_name, :country_code2])
end
end
def encode_hash(hash, encoding = "UTF-8")
hash.inject({}) do |h,i|
h[i[0]] = i[1].is_a?(String) ? i[1].encode(encoding) : i[1]
h
end
end
def format_result(query, attr_names)
if r = ActiveRecord::Base.connection.execute(query).first
r = r.values if r.is_a?(Hash) # some db adapters return Hash, some Array
[Hash[*attr_names.zip(r).flatten]]
else
[]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/baidu_ip.rb | lib/geocoder/lookups/baidu_ip.rb | require 'geocoder/lookups/baidu'
require 'geocoder/results/baidu_ip'
module Geocoder::Lookup
class BaiduIp < Baidu
def name
"Baidu IP"
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://api.map.baidu.com/location/ip?"
end
def content_key
'content'
end
def query_url_params(query)
{
:ip => query.sanitized_text,
:ak => configuration.api_key,
:coor => "bd09ll"
}.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/lookups/ipapi_com.rb | lib/geocoder/lookups/ipapi_com.rb | require 'geocoder/lookups/base'
require 'geocoder/results/ipapi_com'
module Geocoder::Lookup
class IpapiCom < Base
def name
"ip-api.com"
end
def supported_protocols
if configuration.api_key
[:http, :https]
else
[:http]
end
end
private # ----------------------------------------------------------------
def base_query_url(query)
domain = configuration.api_key ? "pro.ip-api.com" : "ip-api.com"
url = "#{protocol}://#{domain}/json/#{query.sanitized_text}"
url << "?" if not url_query_string(query).empty?
url
end
def parse_raw_data(raw_data)
if raw_data.chomp == "invalid key"
invalid_key_result
else
super(raw_data)
end
end
def results(query)
# don't look up a loopback or private address, just return the stored result
return [reserved_result(query.text)] if query.internal_ip_address?
return [] unless doc = fetch_data(query)
if doc["message"] == "invalid key"
raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "Invalid API key.")
return []
else
return [doc]
end
end
def reserved_result(query)
{
"message" => "reserved range",
"query" => query,
"status" => "fail",
"ip" => query,
"city" => "",
"region_code" => "",
"region_name" => "",
"metrocode" => "",
"zipcode" => "",
"latitude" => "0",
"longitude" => "0",
"country_name" => "Reserved",
"country_code" => "RD"
}
end
def invalid_key_result
{
"message" => "invalid key"
}
end
def query_url_params(query)
params = {}
params.merge!(fields: configuration[:fields]) if configuration.has_key?(:fields)
params.merge!(key: configuration.api_key) if configuration.api_key
params.merge(super)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/cache_stores/generic.rb | lib/geocoder/cache_stores/generic.rb | require 'geocoder/cache_stores/base'
module Geocoder::CacheStore
class Generic < Base
def write(url, value)
case
when store.respond_to?(:[]=)
store[key_for(url)] = value
when store.respond_to?(:set)
store.set key_for(url), value
when store.respond_to?(:write)
store.write key_for(url), value
end
end
def read(url)
case
when store.respond_to?(:[])
store[key_for(url)]
when store.respond_to?(:get)
store.get key_for(url)
when store.respond_to?(:read)
store.read key_for(url)
end
end
def keys
store.keys
end
def remove(key)
store.delete(key)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/cache_stores/redis.rb | lib/geocoder/cache_stores/redis.rb | require 'geocoder/cache_stores/base'
module Geocoder::CacheStore
class Redis < Base
def initialize(store, options)
super
@expiration = options[:expiration]
end
def write(url, value, expire = @expiration)
if expire.present?
store.set key_for(url), value, ex: expire
else
store.set key_for(url), value
end
end
def read(url)
store.get key_for(url)
end
def keys
store.keys("#{prefix}*")
end
def remove(key)
store.del(key)
end
private # ----------------------------------------------------------------
def expire; @expiration; end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/cache_stores/base.rb | lib/geocoder/cache_stores/base.rb | module Geocoder::CacheStore
class Base
def initialize(store, options)
@store = store
@config = options
@prefix = config[:prefix]
end
##
# Array of keys with the currently configured prefix
# that have non-nil values.
def keys
store.keys.select { |k| k.match(/^#{prefix}/) and self[k] }
end
##
# Array of cached URLs.
#
def urls
keys
end
protected # ----------------------------------------------------------------
def prefix; @prefix; end
def store; @store; end
def config; @config; end
##
# Cache key for a given URL.
#
def key_for(url)
if url.match(/^#{prefix}/)
url
else
[prefix, url].join
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/models/active_record.rb | lib/geocoder/models/active_record.rb | require 'geocoder/models/base'
module Geocoder
module Model
module ActiveRecord
include Base
##
# Set attribute names and include the Geocoder module.
#
def geocoded_by(address_attr, options = {}, &block)
geocoder_init(
:geocode => true,
:user_address => address_attr,
:latitude => options[:latitude] || :latitude,
:longitude => options[:longitude] || :longitude,
:geocode_block => block,
:units => options[:units],
:method => options[:method],
:lookup => options[:lookup],
:language => options[:language],
:params => options[:params]
)
end
##
# Set attribute names and include the Geocoder module.
#
def reverse_geocoded_by(latitude_attr, longitude_attr, options = {}, &block)
geocoder_init(
:reverse_geocode => true,
:fetched_address => options[:address] || :address,
:latitude => latitude_attr,
:longitude => longitude_attr,
:reverse_block => block,
:units => options[:units],
:method => options[:method],
:lookup => options[:lookup],
:language => options[:language],
:params => options[:params]
)
end
private # --------------------------------------------------------------
def geocoder_file_name; "active_record"; end
def geocoder_module_name; "ActiveRecord"; end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/models/mongoid.rb | lib/geocoder/models/mongoid.rb | require 'geocoder/models/base'
require 'geocoder/models/mongo_base'
module Geocoder
module Model
module Mongoid
include Base
include MongoBase
def self.included(base); base.extend(self); end
private # --------------------------------------------------------------
def geocoder_file_name; "mongoid"; end
def geocoder_module_name; "Mongoid"; end
def geocoder_init(options)
super(options)
if options[:skip_index] == false
# create 2d index
if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= "3"
index({ geocoder_options[:coordinates].to_sym => '2d' },
{:min => -180, :max => 180})
else
index [[ geocoder_options[:coordinates], '2d' ]],
:min => -180, :max => 180
end
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/models/mongo_base.rb | lib/geocoder/models/mongo_base.rb | module Geocoder
##
# Methods for invoking Geocoder in a model.
#
module Model
module MongoBase
##
# Set attribute names and include the Geocoder module.
#
def geocoded_by(address_attr, options = {}, &block)
geocoder_init(
:geocode => true,
:user_address => address_attr,
:coordinates => options[:coordinates] || :coordinates,
:geocode_block => block,
:units => options[:units],
:method => options[:method],
:skip_index => options[:skip_index] || false,
:lookup => options[:lookup],
:language => options[:language]
)
end
##
# Set attribute names and include the Geocoder module.
#
def reverse_geocoded_by(coordinates_attr, options = {}, &block)
geocoder_init(
:reverse_geocode => true,
:fetched_address => options[:address] || :address,
:coordinates => coordinates_attr,
:reverse_block => block,
:units => options[:units],
:method => options[:method],
:skip_index => options[:skip_index] || false,
:lookup => options[:lookup],
:language => options[:language]
)
end
private # ----------------------------------------------------------------
def geocoder_init(options)
unless geocoder_initialized?
@geocoder_options = { }
require "geocoder/stores/#{geocoder_file_name}"
include Geocoder::Store.const_get(geocoder_module_name)
end
@geocoder_options.merge! options
end
def geocoder_initialized?
included_modules.include? Geocoder::Store.const_get(geocoder_module_name)
rescue NameError
false
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/models/base.rb | lib/geocoder/models/base.rb | module Geocoder
##
# Methods for invoking Geocoder in a model.
#
module Model
module Base
def geocoder_options
if defined?(@geocoder_options)
@geocoder_options
elsif superclass.respond_to?(:geocoder_options)
superclass.geocoder_options || { }
else
{ }
end
end
def geocoded_by
fail
end
def reverse_geocoded_by
fail
end
private # ----------------------------------------------------------------
def geocoder_init(options)
unless defined?(@geocoder_options)
@geocoder_options = {}
require "geocoder/stores/#{geocoder_file_name}"
include Geocoder::Store.const_get(geocoder_module_name)
end
@geocoder_options.merge! options
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/models/mongo_mapper.rb | lib/geocoder/models/mongo_mapper.rb | require 'geocoder/models/base'
require 'geocoder/models/mongo_base'
module Geocoder
module Model
module MongoMapper
include Base
include MongoBase
def self.included(base); base.extend(self); end
private # --------------------------------------------------------------
def geocoder_file_name; "mongo_mapper"; end
def geocoder_module_name; "MongoMapper"; end
def geocoder_init(options)
super(options)
if options[:skip_index] == false
ensure_index [[ geocoder_options[:coordinates], Mongo::GEO2D ]],
:min => -180, :max => 180 # create 2d index
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/stores/active_record.rb | lib/geocoder/stores/active_record.rb | # -*- coding: utf-8 -*-
require 'geocoder/sql'
require 'geocoder/stores/base'
##
# Add geocoding functionality to any ActiveRecord object.
#
module Geocoder::Store
module ActiveRecord
include Base
##
# Implementation of 'included' hook method.
#
def self.included(base)
base.extend ClassMethods
base.class_eval do
# scope: geocoded objects
scope :geocoded, lambda {
where("#{table_name}.#{geocoder_options[:latitude]} IS NOT NULL " +
"AND #{table_name}.#{geocoder_options[:longitude]} IS NOT NULL")
}
# scope: not-geocoded objects
scope :not_geocoded, lambda {
where("#{table_name}.#{geocoder_options[:latitude]} IS NULL " +
"OR #{table_name}.#{geocoder_options[:longitude]} IS NULL")
}
# scope: not-reverse geocoded objects
scope :not_reverse_geocoded, lambda {
where("#{table_name}.#{geocoder_options[:fetched_address]} IS NULL")
}
##
# Find all objects within a radius of the given location.
# Location may be either a string to geocode or an array of
# coordinates (<tt>[lat,lon]</tt>). Also takes an options hash
# (see Geocoder::Store::ActiveRecord::ClassMethods.near_scope_options
# for details).
#
scope :near, lambda{ |location, *args|
latitude, longitude = Geocoder::Calculations.extract_coordinates(location)
if Geocoder::Calculations.coordinates_present?(latitude, longitude)
options = near_scope_options(latitude, longitude, *args)
select(options[:select]).where(options[:conditions]).
order(options[:order])
else
# If no lat/lon given we don't want any results, but we still
# need distance and bearing columns so you can add, for example:
# .order("distance")
select(select_clause(nil, null_value, null_value)).where(false_condition)
end
}
##
# Find all objects within the area of a given bounding box.
# Bounds must be an array of locations specifying the southwest
# corner followed by the northeast corner of the box
# (<tt>[[sw_lat, sw_lon], [ne_lat, ne_lon]]</tt>).
#
scope :within_bounding_box, lambda{ |*bounds|
sw_lat, sw_lng, ne_lat, ne_lng = bounds.flatten if bounds
if sw_lat && sw_lng && ne_lat && ne_lng
where(Geocoder::Sql.within_bounding_box(
sw_lat, sw_lng, ne_lat, ne_lng,
full_column_name(geocoder_options[:latitude]),
full_column_name(geocoder_options[:longitude])
))
else
select(select_clause(nil, null_value, null_value)).where(false_condition)
end
}
end
end
##
# Methods which will be class methods of the including class.
#
module ClassMethods
def distance_from_sql(location, *args)
latitude, longitude = Geocoder::Calculations.extract_coordinates(location)
if Geocoder::Calculations.coordinates_present?(latitude, longitude)
distance_sql(latitude, longitude, *args)
end
end
##
# Get options hash suitable for passing to ActiveRecord.find to get
# records within a radius (in kilometers) of the given point.
# Options hash may include:
#
# * +:units+ - <tt>:mi</tt> or <tt>:km</tt>; to be used.
# for interpreting radius as well as the +distance+ attribute which
# is added to each found nearby object.
# Use Geocoder.configure[:units] to configure default units.
# * +:bearing+ - <tt>:linear</tt> or <tt>:spherical</tt>.
# the method to be used for calculating the bearing (direction)
# between the given point and each found nearby point;
# set to false for no bearing calculation. Use
# Geocoder.configure[:distances] to configure default calculation method.
# * +:select+ - string with the SELECT SQL fragment (e.g. “id, name”)
# * +:select_distance+ - whether to include the distance alias in the
# SELECT SQL fragment (e.g. <formula> AS distance)
# * +:select_bearing+ - like +:select_distance+ but for bearing.
# * +:order+ - column(s) for ORDER BY SQL clause; default is distance;
# set to false or nil to omit the ORDER BY clause
# * +:exclude+ - an object to exclude (used by the +nearbys+ method)
# * +:distance_column+ - used to set the column name of the calculated distance.
# * +:bearing_column+ - used to set the column name of the calculated bearing.
# * +:min_radius+ - the value to use as the minimum radius.
# ignored if database is sqlite.
# default is 0.0
#
def near_scope_options(latitude, longitude, radius = 20, options = {})
if options[:units]
options[:units] = options[:units].to_sym
end
latitude_attribute = options[:latitude] || geocoder_options[:latitude]
longitude_attribute = options[:longitude] || geocoder_options[:longitude]
options[:units] ||= (geocoder_options[:units] || Geocoder.config.units)
select_distance = options.fetch(:select_distance) { true }
options[:order] = "" if !select_distance && !options.include?(:order)
select_bearing = options.fetch(:select_bearing) { true }
bearing = bearing_sql(latitude, longitude, options)
distance = distance_sql(latitude, longitude, options)
distance_column = options.fetch(:distance_column) { 'distance' }
bearing_column = options.fetch(:bearing_column) { 'bearing' }
# If radius is a DB column name, bounding box should include
# all rows within the maximum radius appearing in that column.
# Note: performance is dependent on variability of radii.
radius_is_column = radius.is_a?(Symbol) || (defined?(Arel::Nodes::SqlLiteral) && radius.is_a?(Arel::Nodes::SqlLiteral))
bb_radius = radius_is_column ? maximum(radius) : radius
b = Geocoder::Calculations.bounding_box([latitude, longitude], bb_radius, options)
args = b + [
full_column_name(latitude_attribute),
full_column_name(longitude_attribute)
]
bounding_box_conditions = Geocoder::Sql.within_bounding_box(*args)
if using_unextended_sqlite?
conditions = bounding_box_conditions
else
min_radius = options.fetch(:min_radius, 0).to_f
# if radius is a DB column name,
# find rows between min_radius and value in column
if radius_is_column
c = "BETWEEN ? AND #{radius}"
a = [min_radius]
else
c = "BETWEEN ? AND ?"
a = [min_radius, radius]
end
conditions = [bounding_box_conditions + " AND (#{distance}) " + c] + a
end
{
:select => select_clause(options[:select],
select_distance ? distance : nil,
select_bearing ? bearing : nil,
distance_column,
bearing_column),
:conditions => add_exclude_condition(conditions, options[:exclude]),
:order => options.include?(:order) ? options[:order] : "#{distance_column} ASC"
}
end
##
# SQL for calculating distance based on the current database's
# capabilities (trig functions?).
#
def distance_sql(latitude, longitude, options = {})
method_prefix = using_unextended_sqlite? ? "approx" : "full"
Geocoder::Sql.send(
method_prefix + "_distance",
latitude, longitude,
full_column_name(options[:latitude] || geocoder_options[:latitude]),
full_column_name(options[:longitude]|| geocoder_options[:longitude]),
options
)
end
##
# SQL for calculating bearing based on the current database's
# capabilities (trig functions?).
#
def bearing_sql(latitude, longitude, options = {})
if !options.include?(:bearing)
options[:bearing] = Geocoder.config.distances
end
if options[:bearing]
method_prefix = using_unextended_sqlite? ? "approx" : "full"
Geocoder::Sql.send(
method_prefix + "_bearing",
latitude, longitude,
full_column_name(options[:latitude] || geocoder_options[:latitude]),
full_column_name(options[:longitude]|| geocoder_options[:longitude]),
options
)
end
end
##
# Generate the SELECT clause.
#
def select_clause(columns, distance = nil, bearing = nil, distance_column = 'distance', bearing_column = 'bearing')
if columns == :id_only
return full_column_name(primary_key)
elsif columns == :geo_only
clause = ""
else
clause = (columns || full_column_name("*"))
end
if distance
clause += ", " unless clause.empty?
clause += "#{distance} AS #{distance_column}"
end
if bearing
clause += ", " unless clause.empty?
clause += "#{bearing} AS #{bearing_column}"
end
clause
end
##
# Adds a condition to exclude a given object by ID.
# Expects conditions as an array or string. Returns array.
#
def add_exclude_condition(conditions, exclude)
conditions = [conditions] if conditions.is_a?(String)
if exclude
conditions[0] << " AND #{full_column_name(primary_key)} != ?"
conditions << exclude.id
end
conditions
end
def using_unextended_sqlite?
using_sqlite? && !using_sqlite_with_extensions?
end
def using_sqlite?
!!connection.adapter_name.match(/sqlite/i)
end
def using_sqlite_with_extensions?
connection.adapter_name.match(/sqlite/i) &&
defined?(::SqliteExt) &&
%W(MOD POWER SQRT PI SIN COS ASIN ATAN2).all?{ |fn_name|
connection.raw_connection.function_created?(fn_name)
}
end
def using_postgres?
connection.adapter_name.match(/postgres/i)
end
##
# Use OID type when running in PosgreSQL
#
def null_value
using_postgres? ? 'NULL::text' : 'NULL'
end
##
# Value which can be passed to where() to produce no results.
#
def false_condition
using_unextended_sqlite? ? 0 : "false"
end
##
# Prepend table name if column name doesn't already contain one.
#
def full_column_name(column)
column = column.to_s
column.include?(".") ? column : [table_name, column].join(".")
end
end
##
# Get nearby geocoded objects.
# Takes the same options hash as the near class method (scope).
# Returns nil if the object is not geocoded.
#
def nearbys(radius = 20, options = {})
return nil unless geocoded?
options.merge!(:exclude => self) unless send(self.class.primary_key).nil?
self.class.near(self, radius, options)
end
##
# Look up coordinates and assign to +latitude+ and +longitude+ attributes
# (or other as specified in +geocoded_by+). Returns coordinates (array).
#
def geocode
do_lookup(false) do |o,rs|
if r = rs.first
unless r.latitude.nil? or r.longitude.nil?
o.__send__ "#{self.class.geocoder_options[:latitude]}=", r.latitude
o.__send__ "#{self.class.geocoder_options[:longitude]}=", r.longitude
end
r.coordinates
end
end
end
alias_method :fetch_coordinates, :geocode
##
# Look up address and assign to +address+ attribute (or other as specified
# in +reverse_geocoded_by+). Returns address (string).
#
def reverse_geocode
do_lookup(true) do |o,rs|
if r = rs.first
unless r.address.nil?
o.__send__ "#{self.class.geocoder_options[:fetched_address]}=", r.address
end
r.address
end
end
end
alias_method :fetch_address, :reverse_geocode
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/stores/mongoid.rb | lib/geocoder/stores/mongoid.rb | require 'geocoder/stores/base'
require 'geocoder/stores/mongo_base'
module Geocoder::Store
module Mongoid
include Base
include MongoBase
def self.included(base)
MongoBase.included_by_model(base)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/stores/mongo_base.rb | lib/geocoder/stores/mongo_base.rb | module Geocoder::Store
module MongoBase
def self.included_by_model(base)
base.class_eval do
scope :geocoded, lambda {
where(geocoder_options[:coordinates].ne => nil)
}
scope :not_geocoded, lambda {
where(geocoder_options[:coordinates] => nil)
}
end
end
##
# Coordinates [lat,lon] of the object.
# This method always returns coordinates in lat,lon order,
# even though internally they are stored in the opposite order.
#
def to_coordinates
coords = send(self.class.geocoder_options[:coordinates])
coords.is_a?(Array) ? coords.reverse : []
end
##
# Look up coordinates and assign to +latitude+ and +longitude+ attributes
# (or other as specified in +geocoded_by+). Returns coordinates (array).
#
def geocode
do_lookup(false) do |o,rs|
if r = rs.first
unless r.coordinates.nil?
o.__send__ "#{self.class.geocoder_options[:coordinates]}=", r.coordinates.reverse
end
r.coordinates
end
end
end
##
# Look up address and assign to +address+ attribute (or other as specified
# in +reverse_geocoded_by+). Returns address (string).
#
def reverse_geocode
do_lookup(true) do |o,rs|
if r = rs.first
unless r.address.nil?
o.__send__ "#{self.class.geocoder_options[:fetched_address]}=", r.address
end
r.address
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/stores/base.rb | lib/geocoder/stores/base.rb | module Geocoder
module Store
module Base
##
# Is this object geocoded? (Does it have latitude and longitude?)
#
def geocoded?
to_coordinates.compact.size == 2
end
##
# Coordinates [lat,lon] of the object.
#
def to_coordinates
[:latitude, :longitude].map{ |i| send self.class.geocoder_options[i] }
end
##
# Calculate the distance from the object to an arbitrary point.
# See Geocoder::Calculations.distance_between for ways of specifying
# the point. Also takes a symbol specifying the units
# (:mi or :km; can be specified in Geocoder configuration).
#
def distance_to(point, units = nil)
units ||= self.class.geocoder_options[:units]
return nil unless geocoded?
Geocoder::Calculations.distance_between(
to_coordinates, point, :units => units)
end
alias_method :distance_from, :distance_to
##
# Calculate the bearing from the object to another point.
# See Geocoder::Calculations.distance_between for
# ways of specifying the point.
#
def bearing_to(point, options = {})
options[:method] ||= self.class.geocoder_options[:method]
return nil unless geocoded?
Geocoder::Calculations.bearing_between(
to_coordinates, point, options)
end
##
# Calculate the bearing from another point to the object.
# See Geocoder::Calculations.distance_between for
# ways of specifying the point.
#
def bearing_from(point, options = {})
options[:method] ||= self.class.geocoder_options[:method]
return nil unless geocoded?
Geocoder::Calculations.bearing_between(
point, to_coordinates, options)
end
##
# Look up coordinates and assign to +latitude+ and +longitude+ attributes
# (or other as specified in +geocoded_by+). Returns coordinates (array).
#
def geocode
fail
end
##
# Look up address and assign to +address+ attribute (or other as specified
# in +reverse_geocoded_by+). Returns address (string).
#
def reverse_geocode
fail
end
private # --------------------------------------------------------------
##
# Look up geographic data based on object attributes (configured in
# geocoded_by or reverse_geocoded_by) and handle the results with the
# block (given to geocoded_by or reverse_geocoded_by). The block is
# given two-arguments: the object being geocoded and an array of
# Geocoder::Result objects).
#
def do_lookup(reverse = false)
options = self.class.geocoder_options
if reverse and options[:reverse_geocode]
query = to_coordinates
elsif !reverse and options[:geocode]
query = send(options[:user_address])
else
return
end
query_options = [:lookup, :ip_lookup, :language, :params].inject({}) do |hash, key|
if options.has_key?(key)
val = options[key]
hash[key] = val.respond_to?(:call) ? val.call(self) : val
end
hash
end
results = Geocoder.search(query, query_options)
# execute custom block, if specified in configuration
block_key = reverse ? :reverse_block : :geocode_block
if custom_block = options[block_key]
custom_block.call(self, results)
# else execute block passed directly to this method,
# which generally performs the "auto-assigns"
elsif block_given?
yield(self, results)
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/stores/mongo_mapper.rb | lib/geocoder/stores/mongo_mapper.rb | require 'geocoder/stores/base'
require 'geocoder/stores/mongo_base'
module Geocoder::Store
module MongoMapper
include Base
include MongoBase
def self.included(base)
MongoBase.included_by_model(base)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/maxmind.rb | lib/geocoder/results/maxmind.rb | require 'geocoder/results/base'
module Geocoder::Result
class Maxmind < Base
##
# Hash mapping service names to names of returned fields.
#
def self.field_names
{
:country => [
:country_code,
:error
],
:city => [
:country_code,
:region_code,
:city_name,
:latitude,
:longitude,
:error
],
:city_isp_org => [
:country_code,
:region_code,
:city_name,
:postal_code,
:latitude,
:longitude,
:metro_code,
:area_code,
:isp_name,
:organization_name,
:error
],
:omni => [
:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence_factor,
:city_confidence_factor,
:region_confidence_factor,
:postal_confidence_factor,
:error
]
}
end
##
# Name of the MaxMind service being used.
#
def service_name
# it would be much better to infer this from the length of the @data
# array, but MaxMind seems to send inconsistent and wide-ranging response
# lengths (see https://github.com/alexreisner/geocoder/issues/396)
Geocoder.config.maxmind[:service]
end
def field_names
self.class.field_names[service_name]
end
def data_hash
@data_hash ||= Hash[*field_names.zip(@data).flatten]
end
def coordinates
[data_hash[:latitude].to_f, data_hash[:longitude].to_f]
end
def city
data_hash[:city_name]
end
def state # not given by MaxMind
data_hash[:region_name] || data_hash[:region_code]
end
def state_code
data_hash[:region_code]
end
def country #not given by MaxMind
data_hash[:country_name] || data_hash[:country_code]
end
def country_code
data_hash[:country_code]
end
def postal_code
data_hash[:postal_code]
end
def method_missing(method, *args, &block)
if field_names.include?(method)
data_hash[method]
else
super
end
end
def respond_to?(method)
if field_names.include?(method)
true
else
super
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/test.rb | lib/geocoder/results/test.rb | require 'geocoder/results/base'
module Geocoder
module Result
class Test < Base
def self.add_result_attribute(attr)
begin
remove_method(attr) if method_defined?(attr)
rescue NameError # method defined on superclass
end
define_method(attr) do
@data[attr.to_s] || @data[attr.to_sym]
end
end
%w[coordinates neighborhood city state state_code sub_state
sub_state_code province province_code postal_code country
country_code address street_address street_number route geometry].each do |attr|
add_result_attribute(attr)
end
def initialize(data)
data.each_key do |attr|
Test.add_result_attribute(attr)
end
super
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/photon.rb | lib/geocoder/results/photon.rb | require 'geocoder/results/base'
module Geocoder::Result
class Photon < Base
def name
properties['name']
end
def address(_format = :full)
parts = []
parts << name if name
parts << street_address if street_address
parts << city
parts << state if state
parts << postal_code
parts << country
parts.join(', ')
end
def street_address
return unless street
return street unless house_number
"#{house_number} #{street}"
end
def house_number
properties['housenumber']
end
def street
properties['street']
end
def postal_code
properties['postcode']
end
def city
properties['city']
end
def state
properties['state']
end
def state_code
''
end
def country
properties['country']
end
def country_code
''
end
def coordinates
return unless geometry
return unless geometry[:coordinates]
geometry[:coordinates].reverse
end
def geometry
return unless data['geometry']
symbol_hash data['geometry']
end
def bounds
properties['extent']
end
# Type of the result (OSM object type), one of:
#
# :node
# :way
# :relation
#
def type
{
'N' => :node,
'W' => :way,
'R' => :relation
}[properties['osm_type']]
end
def osm_id
properties['osm_id']
end
# See: https://wiki.openstreetmap.org/wiki/Tags
def osm_tag
return unless properties['osm_key']
return properties['osm_key'] unless properties['osm_value']
"#{properties['osm_key']}=#{properties['osm_value']}"
end
private
def properties
@properties ||= data['properties'] || {}
end
def symbol_hash(orig_hash)
{}.tap do |result|
orig_hash.each_key do |key|
next unless orig_hash[key]
result[key.to_sym] = orig_hash[key]
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/smarty_streets.rb | lib/geocoder/results/smarty_streets.rb | require 'geocoder/lookups/base'
module Geocoder::Result
class SmartyStreets < Base
def coordinates
result = %w(latitude longitude).map do |i|
zipcode_endpoint? ? zipcodes.first[i] : metadata[i]
end
if result.compact.empty?
nil
else
result
end
end
def address
parts =
if international_endpoint?
(1..12).map { |i| @data["address#{i}"] }
else
[
delivery_line_1,
delivery_line_2,
last_line
]
end
parts.select{ |i| i.to_s != "" }.join(" ")
end
def state
if international_endpoint?
components['administrative_area']
elsif zipcode_endpoint?
city_states.first['state']
else
components['state_abbreviation']
end
end
def state_code
if international_endpoint?
components['administrative_area']
elsif zipcode_endpoint?
city_states.first['state_abbreviation']
else
components['state_abbreviation']
end
end
def country
international_endpoint? ?
components['country_iso_3'] :
"United States"
end
def country_code
international_endpoint? ?
components['country_iso_3'] :
"US"
end
## Extra methods not in base.rb ------------------------
def street
international_endpoint? ?
components['thoroughfare_name'] :
components['street_name']
end
def city
if international_endpoint?
components['locality']
elsif zipcode_endpoint?
city_states.first['city']
else
components['city_name']
end
end
def zipcode
if international_endpoint?
components['postal_code']
elsif zipcode_endpoint?
zipcodes.first['zipcode']
else
components['zipcode']
end
end
alias_method :postal_code, :zipcode
def zip4
components['plus4_code']
end
alias_method :postal_code_extended, :zip4
def fips
zipcode_endpoint? ?
zipcodes.first['county_fips'] :
metadata['county_fips']
end
def zipcode_endpoint?
zipcodes.any?
end
def international_endpoint?
!@data['address1'].nil?
end
[
:delivery_line_1,
:delivery_line_2,
:last_line,
:delivery_point_barcode,
:addressee
].each do |m|
define_method(m) do
@data[m.to_s] || ''
end
end
[
:components,
:metadata,
:analysis
].each do |m|
define_method(m) do
@data[m.to_s] || {}
end
end
[
:city_states,
:zipcodes
].each do |m|
define_method(m) do
@data[m.to_s] || []
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/amazon_location_service.rb | lib/geocoder/results/amazon_location_service.rb | require 'geocoder/results/base'
module Geocoder::Result
class AmazonLocationService < Base
def initialize(result)
@place = result.place
super
end
def coordinates
[@place.geometry.point[1], @place.geometry.point[0]]
end
def address
@place.label
end
def neighborhood
@place.neighborhood
end
def route
@place.street
end
def city
@place.municipality || @place.sub_region
end
def state
@place.region
end
def state_code
@place.region
end
def province
@place.region
end
def province_code
@place.region
end
def postal_code
@place.postal_code
end
def country
@place.country
end
def country_code
@place.country
end
def place_id
data.place_id if data.respond_to?(:place_id)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/geocodio.rb | lib/geocoder/results/geocodio.rb | require 'geocoder/results/base'
module Geocoder::Result
class Geocodio < Base
def number
address_components["number"]
end
def street
address_components["street"]
end
def suffix
address_components["suffix"]
end
def street_address
[number, address_components["formatted_street"]].compact.join(' ')
end
def state
address_components["state"]
end
alias_method :state_code, :state
def zip
# Postal code is not returned for Canada geocode results
address_components["zip"] || ""
end
alias_method :postal_code, :zip
def country
# Geocodio supports US and Canada, however they don't return the full
# country name.
if country_code == "CA"
"Canada"
else
"United States"
end
end
def country_code
address_components['country']
end
def city
address_components["city"]
end
def postdirectional
address_components["postdirectional"]
end
def location
@data['location']
end
def coordinates
['lat', 'lng'].map{ |i| location[i].to_f } if location
end
def accuracy
@data['accuracy'].to_f if @data.key?('accuracy')
end
def formatted_address(format = :full)
@data['formatted_address']
end
alias_method :address, :formatted_address
private
def address_components
@data['address_components'] || {}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/google_premier.rb | lib/geocoder/results/google_premier.rb | require 'geocoder/results/google'
module Geocoder::Result
class GooglePremier < Google
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.