GithubHelp home page GithubHelp logo

alexreisner / geocoder Goto Github PK

View Code? Open in Web Editor NEW
6.3K 100.0 1.2K 3.01 MB

Complete Ruby geocoding solution.

Home Page: http://www.rubygeocoder.com

License: MIT License

Ruby 100.00%
geocoding geocoding-api geocoding-objects geocoding-requests

geocoder's Introduction

Geocoder

Complete geocoding solution for Ruby.

Gem Version Code Climate

Key features:

  • Forward and reverse geocoding.
  • IP address geocoding.
  • Connects to more than 40 APIs worldwide.
  • Performance-enhancing features like caching.
  • Integrates with ActiveRecord and Mongoid.
  • Basic geospatial queries: search within radius (or rectangle, or ring).

Compatibility:

  • Ruby versions: 2.1+, and JRuby.
  • Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
  • Rails: 5.x, 6.x, and 7.x.
  • Works outside of Rails with the json (for MRI) or json_pure (for JRuby) gem.

Table of Contents

Basic Features:

Advanced Features:

The Rest:

See Also:

Basic Search

In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:

results = Geocoder.search("Paris")
results.first.coordinates
# => [48.856614, 2.3522219]  # latitude and longitude

The reverse is possible too. Given coordinates, it finds an address:

results = Geocoder.search([48.856614, 2.3522219])
results.first.address
# => "Hôtel de Ville, 75004 Paris, France"

You can also look up the location of an IP address:

results = Geocoder.search("172.56.21.89")
results.first.coordinates
# => [30.267153, -97.7430608]
results.first.country
# => "United States"

The success and accuracy of geocoding depends entirely on the API being used to do these lookups. Most queries work fairly well with the default configuration, but every application has different needs and every API has its particular strengths and weaknesses. If you need better coverage for your application you'll want to get familiar with the large number of supported APIs, listed in the API Guide.

Geocoding Objects

To automatically geocode your objects:

1. Your model must provide a method that returns an address to geocode. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: city, state, and country). For example, if your model has street, city, state, and country attributes you might do something like this:

def address
  [street, city, state, country].compact.join(', ')
end

2. Your model must have a way to store latitude/longitude coordinates. With ActiveRecord, add two attributes/columns (of type float or decimal) called latitude and longitude. For MongoDB, use a single field (of type Array) called coordinates (i.e., field :coordinates, type: Array). (See Advanced Model Configuration for using different attribute names.)

3. In your model, tell geocoder where to find the object's address:

geocoded_by :address

This adds a geocode method which you can invoke via callback:

after_validation :geocode

Reverse geocoding (given lat/lon coordinates, find an address) is similar:

reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode

With any geocoded objects, you can do the following:

obj.distance_to([43.9,-98.6])  # distance from obj to point
obj.bearing_to([43.9,-98.6])   # bearing from obj to point
obj.bearing_from(obj2)         # bearing from obj2 to obj

The bearing_from/to methods take a single argument which can be: a [lat,lon] array, a geocoded object, or a geocodable address (string). The distance_from/to methods also take a units argument (:mi, :km, or :nm for nautical miles). See Distance and Bearing below for more info.

One More Thing for MongoDB!

Before you can call geocoded_by you'll need to include the necessary module using one of the following:

include Geocoder::Model::Mongoid
include Geocoder::Model::MongoMapper

Latitude/Longitude Order in MongoDB

Everywhere coordinates are passed to methods as two-element arrays, Geocoder expects them to be in the order: [lat, lon]. However, as per the GeoJSON spec, MongoDB requires that coordinates be stored longitude-first ([lon, lat]), so internally they are stored "backwards." Geocoder's methods attempt to hide this, so calling obj.to_coordinates (a method added to the object by Geocoder via geocoded_by) returns coordinates in the conventional order:

obj.to_coordinates  # => [37.7941013, -122.3951096] # [lat, lon]

whereas calling the object's coordinates attribute directly (obj.coordinates by default) returns the internal representation which is probably the reverse of what you want:

obj.coordinates     # => [-122.3951096, 37.7941013] # [lon, lat]

So, be careful.

Use Outside of Rails

To use Geocoder with ActiveRecord and a framework other than Rails (like Sinatra or Padrino), you will need to add this in your model before calling Geocoder methods:

extend Geocoder::Model::ActiveRecord

Geospatial Database Queries

For ActiveRecord models:

To find objects by location, use the following scopes:

Venue.near('Omaha, NE, US')                   # venues within 20 miles of Omaha
Venue.near([40.71, -100.23], 50)              # venues within 50 miles of a point
Venue.near([40.71, -100.23], 50, units: :km)  # venues within 50 kilometres of a point
Venue.geocoded                                # venues with coordinates
Venue.not_geocoded                            # venues without coordinates

With geocoded objects you can do things like this:

if obj.geocoded?
  obj.nearbys(30)                       # other objects within 30 miles
  obj.distance_from([40.714,-100.234])  # distance from arbitrary point to object
  obj.bearing_to("Paris, France")       # direction from object to arbitrary point
end

For MongoDB-backed models:

Please do not use Geocoder's near method. Instead use MongoDB's built-in geospatial query language, which is faster. Mongoid also provides a DSL for geospatial queries.

Geocoding HTTP Requests

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

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

The location method is vulnerable to trivial IP address spoofing via HTTP headers. If that's a problem for your application, use safe_location instead, but be aware that safe_location will not try to trace a request's originating IP through proxy headers; you will instead get the location of the last proxy the request passed through, if any (excepting any proxies you have explicitly whitelisted in your Rack config).

Note that these methods will usually return nil in test and development environments because things like "localhost" and "0.0.0.0" are not geocodable IP addresses.

Geocoding Service ("Lookup") Configuration

Geocoder supports a variety of street and IP address geocoding services. The default lookups are :nominatim for street addresses and :ipinfo_io for IP addresses. Please see the API Guide for details on specific geocoding services (not all settings are supported by all services).

To create a Rails initializer with sample configuration:

rails generate geocoder:config

Some common options are:

# config/initializers/geocoder.rb
Geocoder.configure(
  # street address geocoding service (default :nominatim)
  lookup: :yandex,

  # IP address geocoding service (default :ipinfo_io)
  ip_lookup: :maxmind,

  # to use an API key:
  api_key: "...",

  # geocoding service request timeout, in seconds (default 3):
  timeout: 5,

  # set default units to kilometers:
  units: :km,

  # caching (see Caching section below for details):
  cache: Redis.new,
  cache_options: {
    expiration: 1.day, # Defaults to `nil`
    prefix: "another_key:" # Defaults to `geocoder:`
  }
)

Please see lib/geocoder/configuration.rb for a complete list of configuration options. Additionally, some lookups have their own special configuration options which are directly supported by Geocoder. For example, to specify a value for Google's bounds parameter:

# with Google:
Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])

Please see the source code for each lookup to learn about directly supported parameters. Parameters which are not directly supported can be specified using the :params option, which appends options to the query string of the geocoding request. For example:

# Nominatim's `countrycodes` parameter:
Geocoder.search("Rome", params: {countrycodes: "us,ca"})

# Google's `region` parameter:
Geocoder.search("Rome", params: {region: "..."})

Configuring Multiple Services

You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:

Geocoder.configure(

  timeout: 2,
  cache: Redis.new,

  yandex: {
    api_key: "...",
    timeout: 5
  },

  baidu: {
    api_key: "..."
  },

  maxmind: {
    api_key: "...",
    service: :omni
  }

)

Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.

Performance and Optimization

Database Indices

In MySQL and Postgres, queries use a bounding box to limit the number of points over which a more precise distance calculation needs to be done. To take advantage of this optimisation, you need to add a composite index on latitude and longitude. In your Rails migration:

add_index :table, [:latitude, :longitude]

In MongoDB, by default, the methods geocoded_by and reverse_geocoded_by create a geospatial index. You can avoid index creation with the :skip_index option, for example:

include Geocoder::Model::Mongoid
geocoded_by :address, skip_index: true

Avoiding Unnecessary API Requests

Geocoding only needs to be performed under certain conditions. To avoid unnecessary work (and quota usage) you will probably want to geocode an object only when:

  • an address is present
  • the address has been changed since last save (or it has never been saved)

The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:

after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }

Caching

When relying on any external service, it's always a good idea to cache retrieved data. When implemented correctly, it improves your app's response time and stability. It's easy to cache geocoding results with Geocoder -- just configure a cache store:

Geocoder.configure(cache: Redis.new)

This example uses Redis, but the cache store can be any object that supports these methods:

  • store#[](key) or #get or #read - retrieves a value
  • store#[]=(key, value) or #set or #write - stores a value
  • store#del(url) - deletes a value
  • store#keys - (Optional) Returns array of keys. Used if you wish to expire the entire cache (see below).

Even a plain Ruby hash will work, though it's not a great choice (cleared out when app is restarted, not shared between app instances, etc).

When using Rails use the Generic cache store as an adapter around Rails.cache:

Geocoder.configure(cache: Geocoder::CacheStore::Generic.new(Rails.cache, {}))

You can also set a custom prefix to be used for cache keys:

Geocoder.configure(cache_options: { prefix: "..." })

By default the prefix is geocoder:

If you need to expire cached content:

Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all)  # expire cached results for current Lookup
Geocoder::Lookup.get(:nominatim).cache.expire("http://...")        # expire cached result for a specific URL
Geocoder::Lookup.get(:nominatim).cache.expire(:all)                # expire cached results for Nominatim
# expire all cached results for all Lookups.
# Be aware that this methods spawns a new Lookup object for each Service
Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}

Do not include the prefix when passing a URL to be expired. Expiring :all will only expire keys with the configured prefix -- it will not expire every entry in your key/value store.

Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service.

Not all services support caching, check the service limitations in the API guide for more information.

Advanced Model Configuration

You are not stuck with the latitude and longitude database column names (with ActiveRecord) or the coordinates array (Mongo) for storing coordinates. For example:

geocoded_by :address, latitude: :lat, longitude: :lon  # ActiveRecord
geocoded_by :address, coordinates: :coords             # MongoDB

For reverse geocoding, you can specify the attribute where the address will be stored. For example:

reverse_geocoded_by :latitude, :longitude, address: :loc    # ActiveRecord
reverse_geocoded_by :coordinates, address: :street_address  # MongoDB

To specify geocoding parameters in your model:

geocoded_by :address, params: {region: "..."}

Supported parameters: :lookup, :ip_lookup, :language, and :params. You can specify an anonymous function if you want to set these on a per-request basis. For example, to use different lookups for objects in different regions:

geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }

def geocoder_lookup
  if country_code == "RU"
    :yandex
  elsif country_code == "CN"
    :baidu
  else
    :nominatim
  end
end

Custom Result Handling

So far we have seen examples where geocoding results are assigned automatically to predefined object attributes. However, you can skip the auto-assignment by providing a block which handles the parsed geocoding results any way you like, for example:

reverse_geocoded_by :latitude, :longitude do |obj,results|
  if geo = results.first
    obj.city    = geo.city
    obj.zipcode = geo.postal_code
    obj.country = geo.country_code
  end
end

after_validation :reverse_geocode

Every Geocoder::Result object, result, provides the following data:

  • result.latitude - float
  • result.longitude - float
  • result.coordinates - array of the above two in the form of [lat,lon]
  • result.address - string
  • result.city - string
  • result.state - string
  • result.state_code - string
  • result.postal_code - string
  • result.country - string
  • result.country_code - string

Most APIs return other data in addition to these globally-supported attributes. To directly access the full response, call the #data method of any Geocoder::Result object. See the API Guide for links to documentation for all geocoding services.

Forward and Reverse Geocoding in the Same Model

You can apply both forward and reverse geocoding to the same model (i.e. users can supply an address or coordinates and Geocoder fills in whatever's missing) but you'll need to provide two different address methods:

  • one for storing the fetched address (when reverse geocoding)
  • one for providing an address to use when fetching coordinates (forward geocoding)

For example:

class Venue
  # build an address from street, city, and state attributes
  geocoded_by :address_from_components

  # store the fetched address in the full_address attribute
  reverse_geocoded_by :latitude, :longitude, address: :full_address
end

The same goes for latitude/longitude. However, for purposes of querying the database, there can be only one authoritative set of latitude/longitude attributes for use in database queries. This is whichever you specify last. For example, here the attributes without the fetched_ prefix will be authoritative:

class Venue
  geocoded_by :address,
    latitude: :fetched_latitude,
    longitude: :fetched_longitude
  reverse_geocoded_by :latitude, :longitude
end

Advanced Database Queries

The following apply to ActiveRecord only. For MongoDB, please use the built-in geospatial features.

The default near search looks for objects within a circle. To search within a doughnut or ring use the :min_radius option:

Venue.near("Austin, TX", 200, min_radius: 40)

To search within a rectangle (note that results will not include distance and bearing attributes):

sw_corner = [40.71, 100.23]
ne_corner = [36.12, 88.65]
Venue.within_bounding_box(sw_corner, ne_corner)

To search for objects near a certain point where each object has a different distance requirement (which is defined in the database), you can pass a column name for the radius:

Venue.near([40.71, 99.23], :effective_radius)

If you store multiple sets of coordinates for each object, you can specify latitude and longitude columns to use for a search:

Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)

Distance and Bearing

When you run a geospatial query, the returned objects have two attributes added:

  • obj.distance - number of miles from the search point to this object
  • obj.bearing - direction from the search point to this object

Results are automatically sorted by distance from the search point, closest to farthest. Bearing is given as a number of degrees clockwise from due north, for example:

  • 0 - due north
  • 180 - due south
  • 90 - due east
  • 270 - due west
  • 230.1 - southwest
  • 359.9 - almost due north

You can convert these to compass point names via provided method:

Geocoder::Calculations.compass_point(355) # => "N"
Geocoder::Calculations.compass_point(45)  # => "NE"
Geocoder::Calculations.compass_point(208) # => "SW"

Note: when running queries on SQLite, distance and bearing are provided for consistency only. They are not very accurate.

For more advanced geospatial querying, please see the rgeo gem.

Geospatial Calculations

The Geocoder::Calculations module contains some useful methods:

# find the distance between two arbitrary points
Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
 => 3619.77359999382 # in configured units (default miles)

# find the geographic center (aka center of gravity) of objects or points
Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
 => [35.14968, -90.048929]

See the code for more!

Batch Geocoding

If you have just added geocoding to an existing application with a lot of objects, you can use this Rake task to geocode them all:

rake geocode:all CLASS=YourModel

If you need reverse geocoding instead, call the task with REVERSE=true:

rake geocode:all CLASS=YourModel REVERSE=true

In either case, it won't try to geocode objects that are already geocoded. The task will print warnings if you exceed the rate limit for your geocoding service. Some services enforce a per-second limit in addition to a per-day limit. To avoid exceeding the per-second limit, you can add a SLEEP option to pause between requests for a given amount of time. You can also load objects in batches to save memory, for example:

rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100

To avoid exceeding per-day limits you can add a LIMIT option. However, this will ignore the BATCH value, if provided.

rake geocode:all CLASS=YourModel LIMIT=1000

Testing

When writing tests for an app that uses Geocoder it may be useful to avoid network calls and have Geocoder return consistent, configurable results. To do this, configure the :test lookup and/or :ip_lookup

Geocoder.configure(lookup: :test, ip_lookup: :test)

Add stubs to define the results that will be returned:

Geocoder::Lookup::Test.add_stub(
  "New York, NY", [
    {
      'coordinates'  => [40.7143528, -74.0059731],
      'address'      => 'New York, NY, USA',
      'state'        => 'New York',
      'state_code'   => 'NY',
      'country'      => 'United States',
      'country_code' => 'US'
    }
  ]
)

With the above stub defined, any query for "New York, NY" will return the results array that follows. You can also set a default stub, to be returned when no other stub matches a given query:

Geocoder::Lookup::Test.set_default_stub(
  [
    {
      'coordinates'  => [40.7143528, -74.0059731],
      'address'      => 'New York, NY, USA',
      'state'        => 'New York',
      'state_code'   => 'NY',
      'country'      => 'United States',
      'country_code' => 'US'
    }
  ]
)

You may also delete a single stub, or reset all stubs including the default stub:

Geocoder::Lookup::Test.delete_stub('New York, NY')
Geocoder::Lookup::Test.reset

Notes:

  • Keys must be strings (not symbols) when calling add_stub or set_default_stub. For example 'country' => not :country =>.
  • The stubbed result objects returned by the Test lookup do not support all the methods real result objects do. If you need to test interaction with real results it may be better to use an external stubbing tool and something like WebMock or VCR to prevent network calls.

Error Handling

By default Geocoder will rescue any exceptions raised by calls to a geocoding service and return an empty array. You can override this on a per-exception basis, and also have Geocoder raise its own exceptions for certain events (eg: API quota exceeded) by using the :always_raise option:

Geocoder.configure(always_raise: [SocketError, Timeout::Error])

You can also do this to raise all exceptions:

Geocoder.configure(always_raise: :all)

The raise-able exceptions are:

SocketError
Timeout::Error
Geocoder::OverQueryLimitError
Geocoder::RequestDenied
Geocoder::InvalidRequest
Geocoder::InvalidApiKey
Geocoder::ServiceUnavailable

Note that only a few of the above exceptions are raised by any given lookup, so there's no guarantee if you configure Geocoder to raise ServiceUnavailable that it will actually be raised under those conditions (because most APIs don't return 503 when they should; you may get a Timeout::Error instead). Please see the source code for your particular lookup for details.

Command Line Interface

When you install the Geocoder gem it adds a geocode command to your shell. You can search for a street address, IP address, postal code, coordinates, etc just like you can with the Geocoder.search method for example:

$ geocode 29.951,-90.081
Latitude:         29.952211
Longitude:        -90.080563
Full address:     1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
City:             New Orleans
State/province:   Louisiana
Postal code:      70112
Country:          United States
Map:              http://maps.google.com/maps?q=29.952211,-90.080563

There are also a number of options for setting the geocoding API, key, and language, viewing the raw JSON response, and more. Please run geocode -h for details.

Technical Discussions

Distance Queries in SQLite

SQLite's lack of trigonometric functions requires an alternate implementation of the near scope. When using SQLite, Geocoder will automatically use a less accurate algorithm for finding objects near a given point. Results of this algorithm should not be trusted too much as it will return objects that are outside the given radius, along with inaccurate distance and bearing calculations.

There are few options for finding objects near a given point in SQLite without installing extensions:

  1. Use a square instead of a circle for finding nearby points. For example, if you want to find points near 40.71, 100.23, search for objects with latitude between 39.71 and 41.71 and longitude between 99.23 and 101.23. One degree of latitude or longitude is at most 69 miles so divide your radius (in miles) by 69.0 to get the amount to add and subtract from your center coordinates to get the upper and lower bounds. The results will not be very accurate (you'll get points outside the desired radius), but you will get all the points within the required radius.

  2. Load all objects into memory and compute distances between them using the Geocoder::Calculations.distance_between method. This will produce accurate results but will be very slow (and use a lot of memory) if you have a lot of objects in your database.

  3. If you have a large number of objects (so you can't use approach #2) and you need accurate results (better than approach #1 will give), you can use a combination of the two. Get all the objects within a square around your center point, and then eliminate the ones that are too far away using Geocoder::Calculations.distance_between.

Because Geocoder needs to provide this functionality as a scope, we must go with option #1, but feel free to implement #2 or #3 if you need more accuracy.

Numeric Data Types and Precision

Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.

A summary of the relationship between geographic precision and the number of decimal places in latitude and longitude degree values is available on Wikipedia. As an example: at the equator, latitude/longitude values with 4 decimal places give about 11 metres precision, whereas 5 decimal places gives roughly 1 metre precision.

Troubleshooting

Mongoid

If you get one of these errors:

uninitialized constant Geocoder::Model::Mongoid
uninitialized constant Geocoder::Model::Mongoid::Mongo

you should check your Gemfile to make sure the Mongoid gem is listed before Geocoder. If Mongoid isn't loaded when Geocoder is initialized, Geocoder will not load support for Mongoid.

ActiveRecord

A lot of debugging time can be saved by understanding how Geocoder works with ActiveRecord. When you use the near scope or the nearbys method of a geocoded object, Geocoder creates an ActiveModel::Relation object which adds some attributes (eg: distance, bearing) to the SELECT clause. It also adds a condition to the WHERE clause to check that distance is within the given radius. Because the SELECT clause is modified, anything else that modifies the SELECT clause may produce strange results, for example:

If you get an error in the above cases, try the following:

# Use the :select option with the near scope to get the columns you want.
# Instead of City.near(...).select(:id, :name), try:
City.near("Omaha, NE", 20, select: "id, name")

# Pass a :select option to the near scope to get the columns you want.
# Then, Ruby's built-in pluck method gets arrays you want.
# Instead of City.near(...).pluck(:id) or City.near(...).ids,, try:
City.near("Omaha, NE", 20, select: "id, name").to_a.pluck(:id, :name)
City.near("Omaha, NE", 20, select: "id").to_a.pluck(:id)

# Pass a :select option to the near scope to get the columns you want.
# Instead of City.near(...).includes(:venues), try:
City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)

# This preload call will normally trigger two queries regardless of the
# number of results; one query on hotels, and one query on administrators.
# Instead of Hotel.near(...).includes(:administrator), try:
Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)

Geocoding is Slow

With most lookups, addresses are translated into coordinates via an API that must be accessed through the Internet. These requests are subject to the same bandwidth constraints as every other HTTP request, and will vary in speed depending on network conditions. Furthermore, many of the services supported by Geocoder are free and thus very popular. Often they cannot keep up with demand and their response times become quite bad.

If your application requires quick geocoding responses you will probably need to pay for a non-free service, or--if you're doing IP address geocoding--use a lookup that doesn't require an external (network-accessed) service.

For IP address lookups in Rails applications, it is generally NOT a good idea to run request.location during a synchronous page load without understanding the speed/behavior of your configured lookup. If the lookup becomes slow, so will your website.

For the most part, the speed of geocoding requests has little to do with the Geocoder gem. Please take the time to learn about your configured lookup before posting performance-related issues.

Unexpected Responses from Geocoding Services

Take a look at the server's raw response. You can do this by getting the request URL in an app console:

Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))

Replace :nominatim with the lookup you are using and replace ... with the address you are trying to geocode. Then visit the returned URL in your web browser. Often the API will return an error message that helps you resolve the problem. If, after reading the raw response, you believe there is a problem with Geocoder, please post an issue and include both the URL and raw response body.

You can also fetch the response in the console:

Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))

Known Issues

Using count with Rails 4.1+

Due to a change in ActiveRecord's count method you will need to use count(:all) to explicitly count all columns ("*") when using a near scope. Using near and calling count with no argument will cause exceptions in many cases.

Using near with includes

You cannot use the near scope with another scope that provides an includes option because the SELECT clause generated by near will overwrite it (or vice versa).

Instead of using includes to reduce the number of database queries, try using joins with either the :select option or a call to preload. For example:

# Pass a :select option to the near scope to get the columns you want.
# Instead of City.near(...).includes(:venues), try:
City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)

# This preload call will normally trigger two queries regardless of the
# number of results; one query on hotels, and one query on administrators.
# Instead of Hotel.near(...).includes(:administrator), try:
Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)

If anyone has a more elegant solution to this problem I am very interested in seeing it.

Using near with objects close to the 180th meridian

The near method will not look across the 180th meridian to find objects close to a given point. In practice this is rarely an issue outside of New Zealand and certain surrounding islands. This problem does not exist with the zero-meridian. The problem is due to a shortcoming of the Haversine formula which Geocoder uses to calculate distances.

Copyright ©️ 2009-2021 Alex Reisner, released under the MIT license.

geocoder's People

Contributors

abravalheri avatar ahukkanen avatar alexreisner avatar anders-e avatar ankane avatar czlee avatar datenimperator avatar drinks avatar empact avatar erdostom avatar exviva avatar fernandomm avatar gonzoyumo avatar hirurg103 avatar iarie avatar ip2location avatar jamesbebbington avatar jcmuller avatar johngallagher avatar kakoni avatar lime avatar minicodemonkey avatar mlandauer avatar petergoldstein avatar rob-murray avatar shqear93 avatar stefanvermaas avatar stevecj avatar trangpham avatar weibel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geocoder's Issues

Limit syntax invalid for PostgreSQL

Got this error when attempting to use geocoder with PostgreSQL.

ActiveRecord::StatementInvalid (PGError: ERROR: LIMIT #,# syntax is not supported
HINT: Use separate LIMIT and OFFSET clauses.
: SELECT count(*) AS count_all FROM "stores" WHERE (latitude BETWEEN 45.0787511144928 AND 46.9628090855073 AND longitude BETWEEN -62.8532709755669 AND -60.1400438244331) LIMIT 0,10)

Bearing between search location & record

We have a mobile app where we wanted to show the direction to the nearest records in our database. Rather than apply the direction methods provided by Geocoder to each record we have added an option to the 'near' method called 'bearing'. If :bearing => :line or :bearing => :spherical is included in the options then an extra column appears showing the bearing from the search point to the record.

Nil Array on :fetch_coordinates

Hey there,

First of all, an absolutely amazing gem! I have used it in a couple of projects now and it has been absolutely incredible!

I have recently switched from the released gem to running from master in order to be able to use the IP geolocation features and I've run into a slight change in behaviour. I have a model User with the fields suburb, state and postcode. I then have geocoder set up within the model using:
geocoded_by :location
def location
[suburb, state, postcode].compact.join(', ')
end
A User doesn't have to specify a suburb, state or postcode on signup. Therefore when after_validation :fetch_coordinates is called, if the User hasn't specified any of the fields required Geocoder is essentially performing:
Geocoder.coordinates(", , ")
Which on master is returning:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.size
Which makes sense as it's looking for a result but finding things a little awkward.
I noticed a similar issue with a blank address was fixed in this commit however before I switched to master, if a User was created with no suburb, state or postcode it didn't make a difference, it just meant that no coordinates were saved and then things carried on. Just wondering if there was a reason for the change and if anyone else has seen this? It took me a while to figure out it was the commas causing all the commotion ahah :P

Cheers, thanks again for an epic gem!

Returning raw data?

Quick question: I am looking to fetch the 'neighborhood' attribute that google maps api can return. I can override one of your fx to do it but was wondering if there is a way to see the raw data returned without overriding your fx?

Address invalid

Everything was working fine initially but after a while I receive a validation error:

"Address invalid"

As it was working initially, could this be due to overloading the API? In which case, would it be possible to add in a list of first/second/third choices in the configuration?
If not, I have no idea why this validation error occurs.

Geocoder stubbing

Hi,

thanks for this very useful gem.

Is there any way to stub actual geocoding while running tests? I know about the http://rubygems.org/gems/vcr, but I'd actually prefer to have a dummy geocoding provider, say FakeGeocoder? What do you think about such idea?

Greetings,
Wojciech

Using :through in a belongs_to relation

Hi,

I don't know if this is really a bug, or only not implemented. But is it possible to use a :through statement in geocoded_by? For example, I have two models, a User and a Location model, and I want to get nearby users of a user.

class User < ActiveRecord::Base
belongs_to :location
geocoded_by :location, :through => :location
end

class Location < ActiveRecord::Base
has_many :users
geocoded_by :address, :latitude => :lat, :longitude => :lon
end

(btw: I know this isn't really the right syntax, just to make myself clear)
So that I can do sth like this:

User.first.nearbys(30);

I don't know if this is possible, but it would be great! ;)
thx!

Geocoder calculations with Mongoid

I am using Mongoid 2.0 and having trouble using the distance calculations of Geocoder. I know MongoDB can do its own geospatial calculations (in 2d only) and that Geocoder overwrites those functions but I am not sure if this is where the problem is coming from.

I have my Location class defined like this: https://gist.github.com/913478

I've used your sample code to display a compass bearing based on a location in my view: https://gist.github.com/913479

I get this error:

Mongo::OperationFailure in Locations#show
can't find special index: 2d for: { coordinates: { $maxDistance: 0.01263023073783309, $nearSphere: [ 0.0, 0.0 ] } }

I thought it could be an error in how the coordinates field was indexed so I ran db.locations.getIndexes() in mongo console and got this result:

{
    "name" : "_id_",
    "ns" : "neighbors_development.locations",
    "key" : {
        "_id" : 1
    },
    "v" : 0
},
{
    "ns" : "neighbors_development.locations",
    "key" : {
        "coords" : "2d"
    },
    "min" : -180,
    "max" : 180,
    "name" : "coords_2d"
},
{
    "ns" : "neighbors_development.locations",
    "unique" : false,
    "key" : {
        "coords" : 1
    },
    "name" : "coords_1",
    "v" : 0
}

Everything looks ok there to me.

I thought maybe it was a problem with my field name "coords" so I changed it to "coordinates" and then got a slightly different error:

Mongo::OperationFailure in Locations#show
missing geo field (coordinates) in : { coordinates: { $maxDistance: 0.01263023073783309, $nearSphere: [ -95.9979883, 41.2523634 ] } }

Am I using the near function incorrectly? Is there a problem with the Mongoid/Geocoder integration?

rake task not working

Hello, I'm in Rails 3.0.3 and I installed the Gem, but the Rake task is not working. Any thoughts? I get an error stating that rake does not know how to build the task geocode.

In addition, for some reason, fetch_coordinates has started returning nil. :( Any thoughts there would be most appreciated as well.

Thanks!

errors when using single table inheritance

I have:

class Org < ActiveRecord::Base

  geocoded_by :location do |obj,results|
    if geo = results.first
      obj.lat = geo.latitude
      obj.lng = geo.longitude
      obj.geo_city  = geo.city
      obj.geo_zip = geo.postal_code
      obj.geo_country = geo.country_code
    end
  end
  after_validation :geocode
end

class Team < Org
end
class League < Org
end

when I instantiate a new Team (with location => 'Dallas, TX') i get the following stacktrace:

You might have expected an instance of Array.
The error occurred while evaluating nil.[]
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/geocoder-0.9.13/lib/geocoder/stores/base.rb:103:in `do_lookup'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/geocoder-0.9.13/lib/geocoder/stores/active_record.rb:201:in `geocode'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activesupport-3.0.7/lib/active_support/callbacks.rb:416:in `_run_validation_callbacks'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activemodel-3.0.7/lib/active_model/validations/callbacks.rb:67:in `run_validations!'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activemodel-3.0.7/lib/active_model/validations.rb:179:in `valid?'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activerecord-3.0.7/lib/active_record/validations.rb:55:in `valid?'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activerecord-3.0.7/lib/active_record/validations.rb:75:in `perform_validations'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activerecord-3.0.7/lib/active_record/validations.rb:43:in `save'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activerecord-3.0.7/lib/active_record/attribute_methods/dirty.rb:21:in `save'
        from /usr/local/rvm/gems/ruby-1.9.2-p136@et/gems/activerecord-3.0.7/lib/active_record/transactions.rb:240:in `block (2 levels) in save'

search fails hard when behind a firewall

Hi there,

This is a very useful gem! :) I'm just using the search functionality as the model integrations were good but too automatic for my use case.

Sometimes I work on-site behind a firewall and I've noticed that that the search method fails hard when it can't access the google geocoder in this way. I haven't tested just without any network connection, but just thought you'd want to know. I'm rescuing from the search just in case a connection issue happens in production, but it'd be nice to catch a specific error rather than the NoMethodError that gets raised in this case :)

Cannot add columns.

There are errors when I add more columns to th Event table. For example when I add Title, Desc and Owner, I get a mysql error. Associations does not work either.

Geocoding API not responding fast enough

I'm trying this simple lookup in rails console:

result = Geocoder.search("74.200.247.59").first
Geocoding API not responding fast enough (see Geocoder::Configuration.timeout to set limit).
 => #<Geocoder::Result::Freegeoip:0x104fa9d80 @data=nil> 

If I try in just in terminal it works fine (and is lighting fast):

geocode 74.200.247.59
Latitude:         33.0347
Longitude:        -96.8134
Full address:     Plano, TX 75093, United States
City:             Plano
State/province:   Texas
Postal code:      75093
Country:          United States
Google map:       http://maps.google.com/maps?q=33.0347,-96.8134

In my rails app or rails console, I always get the same error. I have even set the timeout to 100 seconds but I get the same response.

What could the issue be?

geocoder.rb is:

# geocoding service (see below for supported options):
Geocoder::Configuration.lookup = :google

# to use an API key:
# FIXME:Need to move this to a different key in production
Geocoder::Configuration.api_key = "XXX HIDDEN XXX"

# geocoding service request timeout, in seconds (default 3):
Geocoder::Configuration.timeout = 10

# use HTTPS for geocoding service connections:
Geocoder::Configuration.use_https = true

# language to use (for search queries and reverse geocoding):
Geocoder::Configuration.language = :en

# use a proxy to access the service:
Geocoder::Configuration.http_proxy  = "127.4.4.1"
Geocoder::Configuration.https_proxy = "127.4.4.2" # only if HTTPS is needed

Also, is there a way to set the ip address while in test/development so it isn't always 127.0.0.1 ?

Defferent results from #near and #distance_from

I have in ActiveRecord some object, and when I run on it:
product.distance_from('some street, some city')
I have 5.27 miles, but when I run:
Product.near('some street, some city', 4.8), i have in result also that "product"... so #near and #distance_from is working on some other data or something? when I run Product.near('some street, some city', 4.7), that product isn't returned.

Proposal to extend "nearbys" with "select" argument/option

alex, wanted to share this hopefully before you release 0.9.9. apologies - i don't have a pull request, but this is super quick -

"near" right now allows a number of options/arguments, including "select" which is critical for when you want to do additional joins and pull out columns from other tables.

"nearbys" is another valid case for when you may want to do joins+custom selects - that's exactly what i have run into on my project. right now, nearbys only allows distance and mi/km as arguments. i propose to extend it to allow for the 3rd argument - select. this would require only two lines patched in 0.9.8:

175c175
<     def nearbys(radius = 20, units = :mi, select = nil)

---
>     def nearbys(radius = 20, units = :mi)
177c177
<       options = {:exclude => self, :units => units, :select => select}

---
>       options = {:exclude => self, :units => units}

thanks

Order By Distance?

When performing an ActiveRecord query, is there a way to order the results by distance? If it's not already possible, this would be a really useful feature.

Problems with nearby

I am trying to do a normal Nearby request and I git this error (mysql).

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc,owner HAVING 3956 * 2 * ASIN(SQRT(POWER(SIN((56.0505 - latitude) * PI() ' at line 1: SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN((56.0505 - latitude) * PI() / 180 / 2), 2) + COS(56.0505 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((12.7049 - longitude) * PI() / 180 / 2), 2) )) AS distance FROM events WHERE (latitude BETWEEN 51.7026739130435 AND 60.3983260869565 AND longitude BETWEEN 4.91954263710184 AND 20.4902573628982 AND id != 10) GROUP BY id,address,latitude,longitude,created_at,updated_at,title,desc,owner HAVING 3956 * 2 * ASIN(SQRT(POWER(SIN((56.0505 - latitude) * PI() / 180 / 2), 2) + COS(56.0505 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((12.7049 - longitude) * PI() / 180 / 2), 2) )) <= 300 ORDER BY distance ASC

Problem with results language

Hi! I just tried your cool solution for geocoding - its awesome, but i cant change the results language. I used receipe from the readme with

config/initializers/geocoder.rb

Geocoder::Configuration.language = :de

but there it a error

undefined method `language=' for Geocoder::Configuration:Class

I inspected Geocoder::Configuration.methods and there are no language in them.

How can I change results language?
I use ruby 1.9.2, rails 3.0.5 and geocoder 0.9.10

Order by distance

I can't seem to figure out how to order near results by distance from the search coordinates. How do you do that?

"near" scope's GROUP BY doesn't include other tables' columns

Does the "near" scope not support being used with other scopes that "include" associations (left outer joins to other tables) ?

The exception I get from the SQL generated is:

PGError: ERROR:  column "some_other_table.id" must appear in the GROUP BY clause or be used in an aggregate function ...

I see the following code in "default_near_scope_options" in lib / geocoder / stores / active_record.rb :

:group  => columns.map{ |c| "#{table_name}.#{c.name}" }.join(','),

As far as I can tell, the above line of code only GROUPS BY columns in the geocoded model/table and not others which are included by other "includes" chains on the ActiveRecord::Relation

Is there a known workaround for this limitation?

heroku - operator does not exist: numeric

The near method works great on my localhost but it's throwing this PGError when pushed to heroku.

ActiveRecord::StatementInvalid (PGError: ERROR: operator does not exist: numeric - character varying
LINE 1: ...58.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.358151 - lat) * P...

2011-06-07T09:18:52-07:00 heroku[nginx]: GET /api/v1/locations.json?point=37.358151%2C%20-121.628265%20&radius=24.374397 HTTP/1.1 | 66.192.149.18 | 963 | http | 500
2011-06-07T16:19:12+00:00 app[web.1]: 
2011-06-07T16:19:12+00:00 app[web.1]: 
2011-06-07T16:19:12+00:00 app[web.1]: Started GET "/api/v1/locations.json?point=37.358151%2C%20-121.628265%20&radius=24.374397" for 66.192.149.18 at Tue Jun 07 09:19:12 -0700 2011
2011-06-07T16:19:12+00:00 app[web.1]: 
2011-06-07T16:19:12+00:00 app[web.1]: ActiveRecord::StatementInvalid (PGError: ERROR:  operator does not exist: numeric - character varying
2011-06-07T16:19:12+00:00 app[web.1]: LINE 1: ...58.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.358151 - lat) * P...
2011-06-07T16:19:12+00:00 app[web.1]:                                                              ^
2011-06-07T16:19:12+00:00 app[web.1]: HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
2011-06-07T16:19:12+00:00 app[web.1]: : SELECT  *, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.358151 - lat) * PI() / 180 / 2), 2) + COS(37.358151 * PI() / 180) * COS(lat * PI() / 180) * POWER(SIN((-121.628265 - lng) * PI() / 180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(lng - -121.628265), RADIANS(lat - 37.358151))) + 360 AS decimal) % 360 AS bearing FROM "locations" WHERE (lat BETWEEN 37.0053760059938 AND 37.7109259940062 AND lng BETWEEN -122.072086383576 AND -121.184443616424) GROUP BY locations.id,locations.name,locations.bounding_box,locations.created_at,locations.updated_at,locations.street,locations.postal,locations.city,locations.state,locations.country,locations.description,locations.lat,locations.lng,locations.phone,locations.has_lights,locations.is_free,locations.is_outdoors,locations.are_pads_required,locations.has_concrete,locations.has_wood,locations.cd_page_id HAVING 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.358151 - lat) * PI() / 180 / 2), 2) + COS(37.358151 * PI() / 180) * COS(lat * PI() / 180) * POWER(SIN((-121.6
2011-06-07T16:19:12+00:00 app[web.1]: 28265 - lng) * PI() / 180 / 2), 2) )) <= 24.374397 ORDER BY 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.358151 - lat) * PI() / 180 / 2), 2) + COS(37.358151 * PI() / 180) * COS(lat * PI() / 180) * POWER(SIN((-121.628265 - lng) * PI() / 180 / 2), 2) )) ASC LIMIT 100):

Feature Request: Geocoder.geographic_center with zoom level

Hi,

it would be really useful if Geocoder.geographic_center returns lat, lng, and a zoom level proposal... and by the way: i would prefer an object as result or at least an array with keys.

however: good work so far, your game saved me a lot of time

Geocode binary not present

I installed the geocoder gem in a Rails app using bundler but the geocode command mentioned in the README is not present. I tried running geocode' andbundle exec geocode' to no avail. I'm using bundler 1.0.10 and geocoder 0.9.13 and OSX 10.6.

reverse geocoding bug

if city is not defined in google API (see Nigeria, turkey, etc..) an error occur:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]

any idea about how to skip this, something like
city do not exits put "not found"

i refer to:

reverse_geocoded_by :lat, :lon do |obj,results|
if geo = results.first
obj.city = geo.city
obj.zipcode = geo.postal_code
obj.country = geo.country_code
end
end
after_validation :reverse_geocode

Thank you very much

Francesco

nearby with km as unit calculates wrong limiting distance for query

Location.nearby([53.55, 10], 10, :units => :km)

#The results are limited to a radius of 
#radius * Geocoder::Calculations.km_in_mi

I would expect the limiting radius to be calculated in kms too. I have forked and patched this issue, but I have not found any test addressing the entire behaviour. Am I missing something?

SQLite3::SQLException: near "when": syntax error

I have a 'Venue' model which is geocoded. Triggering Venue.geocoded gives me all Venues back. So far so good.

The moment I call the 'near' method with an array of lat / long + distance (eg. 20) I get a SQLException:

ActiveRecord::StatementInvalid: SQLite3::SQLException: near "when": syntax error: SELECT *, (69.09332411348201 * ABS(latitude - 50.86750240000001) * 0.7071067811865475) + (59.836573914187355 * ABS(longitude - 4.342) * 0.7071067811865475) AS distance, CASE WHEN (latitude >= 50.86750240000001 AND longitude >= 4.342) THEN 45.0 WHEN (latitude < 50.86750240000001 AND longitude >= 4.342) THEN 135.0 WHEN (latitude < 50.86750240000001 AND longitude < 4.342) THEN 225.0 WHEN (latitude >= 50.86750240000001 AND longitude < 4.342) THEN 315.0 END AS bearing FROM "venues" WHERE (latitude BETWEEN 50.578038833778315 AND 51.15696596622171 AND longitude BETWEEN 3.883346400639896 AND 4.800653599360103) GROUP BY venues.id,venues.name,venues.created_at,venues.updated_at,venues.latitude,venues.longitude ORDER BY (69.09332411348201 * ABS(latitude - 50.86750240000001) * 0.7071067811865475) + (59.836573914187355 * ABS(longitude - 4.342) * 0.7071067811865475)

Mongoid integration

This isn't really a bug but more a feature request.
Have you considered making your great plugin mongoid compatible?

NoMethodError in fetch_coordinates comes up randomly (like once every 50 calls to <model>#update)

Thanks again, Alex, for the gem.

The following errors seems to happen randomly (it's probably happened about five or six times to me now, and it happens just kind of randomly during every 50th or so call to users#update)

--- The Error ---
NoMethodError in UsersController#update

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
Rails.root: /Users/Sean/Sites/c3p

Application Trace | Framework Trace | Full Trace
app/models/user.rb:226:in geocode_address' app/controllers/users_controller.rb:73:inupdate'
app/controllers/users_controller.rb:72:in `update'
Request

--- User.rb ----

after_validation :geocode_address
geocoded_by :city

def geocode_address
fetch_coordinates if self[:city]
end


Any ideas? Thanks, Alex.

Cheers.

PostgreSQL + will_paginate incompatibility

  • postgresql 8.4.4
  • rails 3.0.0
  • will_paginate 3.0.pre2
  • rails-geocoder 0.9.5

Pagination breaks the 'distance' column generated in the initial query. I am using the 'near' method and it works great until I add pagination. This is the error I get from PG:

PGError: ERROR: column "distance" does not exist

and this is what my log spits out: http://gist.github.com/652962

nearbys method returns different results with :units option

I have two record @user1, @user2

@distance_miles = @user1.distance_to([@user2.latitude, @user2.longitude])
@distance_kms = @user1.distance_to([@user2.latitude, @user2.longitude], :km)

I get the two records distance in miles and kms units. The value of @distance_miles is 0.425240462464623, the value of @distance_kms is 0.684358187086058.

Now, i use nearbys method on @user1 like this @near_users = @user1.nearbys(0.48). It can return @user2, because 0.48 > 0.425240462464623.But when i pass the :km option like @near_users = @user1.nearbys(0.7, :units => :km), no records return as i expect (0.7 kms > 0.684358187086058). I wonder if it is a bug?

Checking the source code , i found out in def approx_near_scope_options(latitude, longitude, radius, options) method,
radius is converted to miles units when passing :units => :km . But in the method , the two lines below
dx = Geocoder::Calculations.longitude_degree_distance(30, options[:units] || :mi)
dy = Geocoder::Calculations.latitude_degree_distance(options[:units] || :mi)
are still using the options[:units].As you can see, radius is now miles units , but longitude_degree_distance and latitude_degree_distance are using options[:units] which is :km.I don't know if it is a bug?

geo.postal_code fails

I am getting

undefined method `postal_code' for #Array:0x103130700

when running this code. The examples on rubygeocoder.com show geo.postal_code being used. Could you help me understand why this is failing and how to fix?

reverse_geocoded_by :coords do |location, geo|
location.lat = geo.latitude
location.lon = geo.longitude
location.full_street_address = geo.address
location.city = geo.city
location.coords = geo.coordinates
location.post_code = geo.postal_code
location.country_name = geo.country
location.country_code = geo.country_code
end

nearbys method sqj syntax error

hopefully this report is less bogus:

Venue Load (14.9ms) SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN((41.8757476 - latitude) * PI() / 180 / 2), 2) + COS(41.8757476 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((-87.6205898 - longitude) * PI() / 180 / 2), 2) )) AS distance FROM "venues" WHERE ((latitude BETWEEN 41.84676209275362 AND 41.90473310724637 AND longitude BETWEEN -87.65951772705726 AND -87.58166187294275) AND id != 1) HAVING 3956 * 2 * ASIN(SQRT(POWER(SIN((41.8757476 - latitude) * PI() / 180 / 2), 2) + COS(41.8757476 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((-87.6205898 - longitude) * PI() / 180 / 2), 2) )) <= 2 ORDER BY distance ASC
PGError: ERROR: column "venues.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN((41.8757476 - l...
^
: SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN((41.8757476 - latitude) * PI() / 180 / 2), 2) + COS(41.8757476 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((-87.6205898 - longitude) * PI() / 180 / 2), 2) )) AS distance FROM "venues" WHERE ((latitude BETWEEN 41.84676209275362 AND 41.90473310724637 AND longitude BETWEEN -87.65951772705726 AND -87.58166187294275) AND id != 1) HAVING 3956 * 2 * ASIN(SQRT(POWER(SIN((41.8757476 - latitude) * PI() / 180 / 2), 2) + COS(41.8757476 * PI()/180) * COS(latitude * PI() / 180) * POWER(SIN((-87.6205898 - longitude) * PI() / 180 / 2), 2) )) <= 2 ORDER BY distance ASC

NoMethodError (undefined method `-' for "45.000000":String):

when i call obj.nearbys locally in webrick, everything is fine,
when it is called on my server i get this error "NoMethodError (undefined method `-' for "45.000000":String):"
when i call it in the rails console on my server it works.

best regards,
simon

result always return 1 item, used to work but something broke...

Hello,

I am doing a simple Geocode.serch(param[:search]) type query and I am getting and error on @result.count

undefined method `count' for #Geocoder::Result::Google:0x00000104af6518

This is my model:

class Geosearch
def get_location_of(search_param)
result = Geocoder.search(search_param)
end
end

This is my controller:

def new
unless params[:search].blank?
@geosearch = Geosearch.new
@search_result = @geosearch.get_location_of(params[:search])
end

@map = Map.new

respond_to do |format|
  format.html # new.html.erb
  format.xml  { render :xml => @map }
end

end

And this is my view, where the error happens:

result-wrap

  • if !@search_result.blank? and @search_result.count > 1

basically, I noticed that since I rebooted my server all geocoding searches return one result, and a count can't be performed on the result instance variable.

The same code used to work about an hour ago... is this a google response problem? Or has some setting in my app changed?

I'm confused!

this is an example result return if it helps with anything:

Parameters: {"utf8"=>"✓", "search"=>"test", "commit"=>"Search"}

--- !ruby/object:Geocoder::Result::Google
data:
types:

  • route
    formatted_address: Test, North Hidalgo, NM 85534, USA
    address_components:
  • long_name: Test
    short_name: Test
    types:
    • route
  • long_name: North Hidalgo
    short_name: North Hidalgo
    types:
    • administrative_area_level_3
    • political
  • long_name: Hidalgo
    short_name: Hidalgo
    types:
    • administrative_area_level_2
    • political
  • long_name: New Mexico
    short_name: NM
    types:
    • administrative_area_level_1
    • political
  • long_name: United States
    short_name: US
    types:
    • country
    • political
  • long_name: "85534"
    short_name: "85534"
    types:
    • postal_code
      geometry:
      location:
      lat: 32.6144704
      lng: -108.9852073
      location_type: GEOMETRIC_CENTER
      viewport:
      southwest:
      lat: 32.6121267
      lng: -108.9883778
      northeast:
      lat: 32.618422
      lng: -108.9820826
      bounds:
      southwest:
      lat: 32.6140596
      lng: -108.9876933
      northeast:
      lat: 32.6164891
      lng: -108.9827671

32.6144704
-108.9852073
[32.6144704, -108.9852073]
Test, North Hidalgo, NM 85534, USA

Cannot get near_scope to return values

Doing Venue.near('Omaha, NE, US', 20) or Venue.near([40.71, 100.23], 20) is always returning an empty array. I am using Mysql 5.1.49 on Ubuntu. Model is setup properly with geocoded_by :full_address

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.