geocoder 1.4.3 → 1.6.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (109) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +64 -0
  3. data/LICENSE +1 -1
  4. data/README.md +365 -883
  5. data/examples/autoexpire_cache_redis.rb +5 -3
  6. data/lib/generators/geocoder/config/templates/initializer.rb +3 -2
  7. data/lib/generators/geocoder/maxmind/geolite_city_generator.rb +2 -0
  8. data/lib/generators/geocoder/maxmind/geolite_country_generator.rb +2 -0
  9. data/lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb +1 -1
  10. data/lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb +1 -1
  11. data/lib/generators/geocoder/migration_version.rb +15 -0
  12. data/lib/geocoder/cache.rb +6 -2
  13. data/lib/geocoder/calculations.rb +1 -1
  14. data/lib/geocoder/cli.rb +2 -2
  15. data/lib/geocoder/configuration.rb +2 -2
  16. data/lib/geocoder/exceptions.rb +1 -1
  17. data/lib/geocoder/ip_address.rb +14 -1
  18. data/lib/geocoder/lookup.rb +13 -6
  19. data/lib/geocoder/lookups/amap.rb +63 -0
  20. data/lib/geocoder/lookups/baidu.rb +14 -10
  21. data/lib/geocoder/lookups/baidu_ip.rb +7 -36
  22. data/lib/geocoder/lookups/ban_data_gouv_fr.rb +17 -4
  23. data/lib/geocoder/lookups/base.rb +28 -5
  24. data/lib/geocoder/lookups/bing.rb +15 -13
  25. data/lib/geocoder/lookups/db_ip_com.rb +52 -0
  26. data/lib/geocoder/lookups/dstk.rb +4 -2
  27. data/lib/geocoder/lookups/esri.rb +39 -29
  28. data/lib/geocoder/lookups/freegeoip.rb +16 -7
  29. data/lib/geocoder/lookups/geocoder_ca.rb +4 -4
  30. data/lib/geocoder/lookups/geocodio.rb +5 -5
  31. data/lib/geocoder/lookups/geoportail_lu.rb +7 -7
  32. data/lib/geocoder/lookups/google.rb +13 -9
  33. data/lib/geocoder/lookups/google_places_details.rb +4 -4
  34. data/lib/geocoder/lookups/google_places_search.rb +4 -4
  35. data/lib/geocoder/lookups/google_premier.rb +11 -1
  36. data/lib/geocoder/lookups/here.rb +29 -23
  37. data/lib/geocoder/lookups/ip2location.rb +67 -0
  38. data/lib/geocoder/lookups/ipapi_com.rb +9 -13
  39. data/lib/geocoder/lookups/ipdata_co.rb +62 -0
  40. data/lib/geocoder/lookups/ipgeolocation.rb +51 -0
  41. data/lib/geocoder/lookups/ipinfo_io.rb +11 -29
  42. data/lib/geocoder/lookups/ipregistry.rb +68 -0
  43. data/lib/geocoder/lookups/ipstack.rb +63 -0
  44. data/lib/geocoder/lookups/latlon.rb +4 -4
  45. data/lib/geocoder/lookups/location_iq.rb +26 -8
  46. data/lib/geocoder/lookups/mapbox.rb +12 -6
  47. data/lib/geocoder/lookups/mapquest.rb +4 -5
  48. data/lib/geocoder/lookups/maxmind.rb +6 -6
  49. data/lib/geocoder/lookups/maxmind_geoip2.rb +8 -7
  50. data/lib/geocoder/lookups/nominatim.rb +17 -5
  51. data/lib/geocoder/lookups/opencagedata.rb +7 -6
  52. data/lib/geocoder/lookups/osmnames.rb +57 -0
  53. data/lib/geocoder/lookups/pelias.rb +8 -9
  54. data/lib/geocoder/lookups/pickpoint.rb +41 -0
  55. data/lib/geocoder/lookups/pointpin.rb +10 -9
  56. data/lib/geocoder/lookups/postcode_anywhere_uk.rb +4 -5
  57. data/lib/geocoder/lookups/postcodes_io.rb +31 -0
  58. data/lib/geocoder/lookups/smarty_streets.rb +20 -10
  59. data/lib/geocoder/lookups/telize.rb +26 -6
  60. data/lib/geocoder/lookups/tencent.rb +59 -0
  61. data/lib/geocoder/lookups/yandex.rb +12 -8
  62. data/lib/geocoder/models/active_record.rb +4 -3
  63. data/lib/geocoder/query.rb +14 -0
  64. data/lib/geocoder/railtie.rb +1 -1
  65. data/lib/geocoder/request.rb +32 -0
  66. data/lib/geocoder/results/amap.rb +87 -0
  67. data/lib/geocoder/results/baidu.rb +10 -14
  68. data/lib/geocoder/results/ban_data_gouv_fr.rb +1 -1
  69. data/lib/geocoder/results/base.rb +13 -1
  70. data/lib/geocoder/results/bing.rb +1 -1
  71. data/lib/geocoder/results/db_ip_com.rb +58 -0
  72. data/lib/geocoder/results/freegeoip.rb +0 -5
  73. data/lib/geocoder/results/geocoder_ca.rb +3 -3
  74. data/lib/geocoder/results/geoip2.rb +24 -10
  75. data/lib/geocoder/results/geoportail_lu.rb +5 -3
  76. data/lib/geocoder/results/google.rb +16 -5
  77. data/lib/geocoder/results/here.rb +12 -1
  78. data/lib/geocoder/results/ip2location.rb +22 -0
  79. data/lib/geocoder/results/ipdata_co.rb +40 -0
  80. data/lib/geocoder/results/ipgeolocation.rb +59 -0
  81. data/lib/geocoder/results/ipregistry.rb +308 -0
  82. data/lib/geocoder/results/ipstack.rb +60 -0
  83. data/lib/geocoder/results/maxmind.rb +0 -5
  84. data/lib/geocoder/results/maxmind_local.rb +0 -5
  85. data/lib/geocoder/results/nominatim.rb +12 -0
  86. data/lib/geocoder/results/opencagedata.rb +12 -2
  87. data/lib/geocoder/results/osmnames.rb +56 -0
  88. data/lib/geocoder/results/pickpoint.rb +6 -0
  89. data/lib/geocoder/results/postcodes_io.rb +40 -0
  90. data/lib/geocoder/results/smarty_streets.rb +55 -19
  91. data/lib/geocoder/results/telize.rb +0 -5
  92. data/lib/geocoder/results/tencent.rb +72 -0
  93. data/lib/geocoder/results/test.rb +1 -1
  94. data/lib/geocoder/sql.rb +4 -4
  95. data/lib/geocoder/stores/active_record.rb +16 -5
  96. data/lib/geocoder/stores/base.rb +1 -2
  97. data/lib/geocoder/version.rb +1 -1
  98. data/lib/hash_recursive_merge.rb +1 -2
  99. data/lib/maxmind_database.rb +3 -3
  100. data/lib/tasks/geocoder.rake +11 -3
  101. metadata +30 -14
  102. data/lib/geocoder/lookups/geocoder_us.rb +0 -43
  103. data/lib/geocoder/lookups/mapzen.rb +0 -15
  104. data/lib/geocoder/lookups/okf.rb +0 -44
  105. data/lib/geocoder/lookups/ovi.rb +0 -62
  106. data/lib/geocoder/results/geocoder_us.rb +0 -39
  107. data/lib/geocoder/results/mapzen.rb +0 -5
  108. data/lib/geocoder/results/okf.rb +0 -106
  109. data/lib/geocoder/results/ovi.rb +0 -71
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: f394e733415900303ed8be35b91692886c134ffb
4
- data.tar.gz: 21211fb7e4b78a3f957923fabe959af3e9073c4f
2
+ SHA256:
3
+ metadata.gz: 25d03f1aeb92b80a0ec269a1f42093bb641e468d0824d324ad5157ed9cfcb559
4
+ data.tar.gz: 1a23a47bfb3d4af0de14421f8b1b76e03234aee309a8be7ddb2acd91ce04c30d
5
5
  SHA512:
6
- metadata.gz: 628aa577898b95b9a5674f2b8f97452c04744eebbe80af4a90372f5461bde24a217408dc5c06b2e99213907ee91e4beead63e51cf69e0631a1b6b42a7085e7f7
7
- data.tar.gz: fad11275dbbcc8a897b9d5b9231ceb543d0b81341745aaadd5033f93950af21cf04ea2bb93f0c8242d7c81a317b1eccf4be984d2b3bae9c3cb879b1fac02510a
6
+ metadata.gz: e8f4fd2a60fa6ccb91f7a04a737b5720aa4e276181c202b215b5dd8c50b1746d833ace8c2a034aae1282132e62f96be518b3b366c34f03c73ffcb4cf1dd3c6ab
7
+ data.tar.gz: 848c835773fd172b8469eefc28646c4c5cd3176d10bfb175f5d447bd24b51982555644b7ff5d45eddb2bc04cf7820fadb2363a23cf907ad13aa930f33b5dad09
@@ -3,6 +3,70 @@ Changelog
3
3
 
4
4
  Major changes to Geocoder for each release. Please see the Git log for complete list of changes.
5
5
 
6
+ 1.6.1 (2020 Jan 23)
7
+ -------------------
8
+ * Sanitize lat/lon values passed to within_bounding_box to prevent SQL injection.
9
+
10
+ 1.6.0 (2020 Jan 6)
11
+ -------------------
12
+ * Drop support for Rails 3.x.
13
+ * Add support for :osmnames lookup (thanks github.com/zacviandier).
14
+ * Add support for :ipgeolocation IP lookup (thanks github.com/ahsannawaz111).
15
+
16
+ 1.5.2 (2019 Oct 3)
17
+ -------------------
18
+ * Add support for :ipregistry lookup (thanks github.com/ipregistry).
19
+ * Various fixes for Yandex lookup.
20
+
21
+ 1.5.1 (2019 Jan 23)
22
+ -------------------
23
+ * Add support for :tencent lookup (thanks github.com/Anders-E).
24
+ * Add support for :smarty_streets international API (thanks github.com/ankane).
25
+ * Remove :mapzen lookup.
26
+
27
+ 1.5.0 (2018 Jul 31)
28
+ -------------------
29
+ * Drop support for Ruby <2.0.
30
+ * Change default street address lookup from :google to :nominatim.
31
+ * Cache keys no longer include API credentials. This means many entries in existing cache implementations will be invalidated.
32
+ * Test lookup fixtures should now return `coordinates` and NOT `latitude`/`longitude` attributes (see #1258). This may break some people's tests.
33
+ * Add support for :ip2location lookup (thanks github.com/ip2location).
34
+ * Remove :ovi and :okf lookups.
35
+
36
+ 1.4.9 (2018 May 27)
37
+ -------------------
38
+ * Fix regression in :geoip2 lookup.
39
+ * Add support for Postcodes.io lookup (thanks github.com/sledge909).
40
+
41
+ 1.4.8 (2018 May 21)
42
+ -------------------
43
+ * Change default IP address lookup from :freegeoip to :ipinfo_io.
44
+ * Add support for :ipstack lookup (thanks github.com/Heath101).
45
+ * Fix incompatibility with redis-rb gem v4.0.
46
+
47
+ 1.4.7 (2018 Mar 13)
48
+ -------------------
49
+ * Allow HTTP protocol for Nominatim.
50
+
51
+ 1.4.6 (2018 Feb 28)
52
+ -------------------
53
+ * Add support for :ipdata_co lookup (thanks github.com/roschaefer).
54
+ * Update for Rails 5.2 compatibility (thanks github.com/stevenharman).
55
+
56
+ 1.4.5 (2017 Nov 29)
57
+ -------------------
58
+ * Add support for :pickpoint lookup (thanks github.com/cylon-v).
59
+ * Add support for :db_ip_com lookup (thanks github.com/cv).
60
+ * Change FreeGeoIP host to freegeoip.net.
61
+ * Allow search radius to be a symbol representing a column in DB (thanks github.com/leonelgalan).
62
+ * Add support for new parameters and improved error handling for several lookups.
63
+ * Fix bug in SQL when searching for objects across 180th meridian.
64
+
65
+ 1.4.4 (2017 May 17)
66
+ -------------------
67
+ * Use HTTPS by default for :freegeoip (thanks github.com/mehanoid).
68
+ * Add support for :amap lookup (thanks github.com/pzgz).
69
+
6
70
  1.4.3 (2017 Feb 7)
7
71
  -------------------
8
72
  * Add :google_places_search lookup (thanks github.com/waruboy).
data/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2009-11 Alex Reisner
1
+ Copyright (c) 2009-2020 Alex Reisner
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,133 +1,178 @@
1
1
  Geocoder
2
2
  ========
3
3
 
4
- Geocoder is a complete geocoding solution for Ruby. With Rails, it adds geocoding (by street or IP address), reverse geocoding (finding street address based on given coordinates), and distance queries. It's as simple as calling `geocode` on your objects, and then using a scope like `Venue.near("Billings, MT")`.
4
+ **Complete geocoding solution for Ruby.**
5
5
 
6
- _Please note that this README is for the current `HEAD` and may document features not present in the latest gem release. For this reason, you may want to instead view the README for your [particular version](https://github.com/alexreisner/geocoder/releases)._
6
+ [![Gem Version](https://badge.fury.io/rb/geocoder.svg)](http://badge.fury.io/rb/geocoder)
7
+ [![Code Climate](https://codeclimate.com/github/alexreisner/geocoder/badges/gpa.svg)](https://codeclimate.com/github/alexreisner/geocoder)
8
+ [![Build Status](https://travis-ci.org/alexreisner/geocoder.svg?branch=master)](https://travis-ci.org/alexreisner/geocoder)
7
9
 
10
+ Key features:
8
11
 
9
- Compatibility
10
- -------------
12
+ * Forward and reverse geocoding.
13
+ * IP address geocoding.
14
+ * Connects to more than 40 APIs worldwide.
15
+ * Performance-enhancing features like caching.
16
+ * Integrates with ActiveRecord and Mongoid.
17
+ * Basic geospatial queries: search within radius (or rectangle, or ring).
11
18
 
12
- * Supports multiple Ruby versions: Ruby 1.9.3, 2.x, and JRuby.
13
- * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
14
- * Supports Rails 3, 4, and 5. If you need to use it with Rails 2 please see the `rails2` branch (no longer maintained, limited feature set).
15
- * Works very well outside of Rails, you just need to install either the `json` (for MRI) or `json_pure` (for JRuby) gem.
19
+ Compatibility:
16
20
 
21
+ * Ruby versions: 2.x, and JRuby.
22
+ * Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
23
+ * Rails: 4, 5, and 6.
24
+ * Works outside of Rails with the `json` (for MRI) or `json_pure` (for JRuby) gem.
17
25
 
18
- Note on Rails 4.1 and Greater
19
- -----------------------------
20
-
21
- Due to [a change in ActiveRecord's `count` method](https://github.com/rails/rails/pull/10710) 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.
22
26
 
27
+ Table of Contents
28
+ -----------------
23
29
 
24
- Installation
25
- ------------
30
+ Basic Features:
26
31
 
27
- Install Geocoder like any other Ruby gem:
32
+ * [Basic Search](#basic-search)
33
+ * [Geocoding Objects](#geocoding-objects)
34
+ * [Geospatial Database Queries](#geospatial-database-queries)
35
+ * [Geocoding HTTP Requests](#geocoding-http-requests)
36
+ * [Geocoding Service ("Lookup") Configuration](#geocoding-service-lookup-configuration)
28
37
 
29
- gem install geocoder
38
+ Advanced Features:
30
39
 
31
- Or, if you're using Rails/Bundler, add this to your Gemfile:
40
+ * [Performance and Optimization](#performance-and-optimization)
41
+ * [Advanced Model Configuration](#advanced-model-configuration)
42
+ * [Advanced Database Queries](#advanced-database-queries)
43
+ * [Geospatial Calculations](#geospatial-calculations)
44
+ * [Batch Geocoding](#batch-geocoding)
45
+ * [Testing](#testing)
46
+ * [Error Handling](#error-handling)
47
+ * [Command Line Interface](#command-line-interface)
32
48
 
33
- gem 'geocoder'
49
+ The Rest:
34
50
 
35
- and run at the command prompt:
51
+ * [Technical Discussions](#technical-discussions)
52
+ * [Troubleshooting](#troubleshooting)
53
+ * [Known Issues](#known-issues)
54
+ * [Reporting Issues](#reporting-issues)
55
+ * [Contributing](#contributing)
36
56
 
37
- bundle install
57
+ See Also:
38
58
 
59
+ * [Guide to Geocoding APIs](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) (formerly part of this README)
39
60
 
40
- Object Geocoding
41
- ----------------
42
61
 
43
- ### ActiveRecord
62
+ Basic Search
63
+ ------------
44
64
 
45
- Your model must have two attributes (database columns) for storing latitude and longitude coordinates. By default they should be called `latitude` and `longitude` but this can be changed (see "Model Configuration" below):
65
+ In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:
46
66
 
47
- rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
48
- rake db:migrate
67
+ results = Geocoder.search("Paris")
68
+ results.first.coordinates
69
+ => [48.856614, 2.3522219] # latitude and longitude
49
70
 
50
- For geocoding, your model must provide a method that returns an address. 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`).
71
+ The reverse is possible too. Given coordinates, it finds an address:
51
72
 
52
- Next, your model must tell Geocoder which method returns your object's geocodable address:
73
+ results = Geocoder.search([48.856614, 2.3522219])
74
+ results.first.address
75
+ => "Hôtel de Ville, 75004 Paris, France"
53
76
 
54
- geocoded_by :full_street_address # can also be an IP address
55
- after_validation :geocode # auto-fetch coordinates
77
+ You can also look up the location of an IP addresses:
56
78
 
57
- For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
79
+ results = Geocoder.search("172.56.21.89")
80
+ results.first.coordinates
81
+ => [30.267153, -97.7430608]
82
+ results.first.country
83
+ => "United States"
58
84
 
59
- reverse_geocoded_by :latitude, :longitude
60
- after_validation :reverse_geocode # auto-fetch address
85
+ **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](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md).
61
86
 
62
- ### Mongoid
63
87
 
64
- First, your model must have an array field for storing coordinates:
88
+ Geocoding Objects
89
+ -----------------
65
90
 
66
- field :coordinates, :type => Array
91
+ To automatically geocode your objects:
67
92
 
68
- You may also want an address field, like this:
93
+ **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:
69
94
 
70
- field :address
95
+ def address
96
+ [street, city, state, country].compact.join(', ')
97
+ end
71
98
 
72
- but if you store address components (city, state, country, etc) in separate fields you can instead define a method called `address` that combines them into a single string which will be used to query the geocoding service.
99
+ **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](#advanced-model-configuration) for using different attribute names.)
73
100
 
74
- Once your fields are defined, include the `Geocoder::Model::Mongoid` module and then call `geocoded_by`:
101
+ **3.** In your model, tell geocoder where to find the object's address:
75
102
 
76
- include Geocoder::Model::Mongoid
77
- geocoded_by :address # can also be an IP address
78
- after_validation :geocode # auto-fetch coordinates
103
+ geocoded_by :address
79
104
 
80
- Reverse geocoding is similar:
105
+ This adds a `geocode` method which you can invoke via callback:
81
106
 
82
- include Geocoder::Model::Mongoid
83
- reverse_geocoded_by :coordinates
84
- after_validation :reverse_geocode # auto-fetch address
107
+ after_validation :geocode
85
108
 
86
- Once you've set up your model you'll need to create the necessary spatial indices in your database:
109
+ Reverse geocoding (given lat/lon coordinates, find an address) is similar:
87
110
 
88
- rake db:mongoid:create_indexes
111
+ reverse_geocoded_by :latitude, :longitude
112
+ after_validation :reverse_geocode
89
113
 
90
- Be sure to read _Latitude/Longitude Order_ in the _Notes on MongoDB_ section below on how to properly retrieve latitude/longitude coordinates from your objects.
114
+ With any geocoded objects, you can do the following:
91
115
 
92
- ### MongoMapper
116
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
117
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
118
+ obj.bearing_from(obj2) # bearing from obj2 to obj
93
119
 
94
- MongoMapper is very similar to Mongoid, just be sure to include `Geocoder::Model::MongoMapper`.
120
+ 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](#distance-and-bearing) below for more info.
95
121
 
96
- ### Mongo Indices
122
+ ### One More Thing for MongoDB!
97
123
 
98
- 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:
124
+ Before you can call `geocoded_by` you'll need to include the necessary module using one of the following:
99
125
 
100
126
  include Geocoder::Model::Mongoid
101
- geocoded_by :address, :skip_index => true
127
+ include Geocoder::Model::MongoMapper
102
128
 
103
- ### Bulk Geocoding
129
+ ### Latitude/Longitude Order in MongoDB
104
130
 
105
- 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:
131
+ 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](http://geojson.org/geojson-spec.html#positions), 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:
106
132
 
107
- rake geocode:all CLASS=YourModel
133
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
108
134
 
109
- If you need reverse geocoding instead, call the task with REVERSE=true:
135
+ 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:
110
136
 
111
- rake geocode:all CLASS=YourModel REVERSE=true
137
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
112
138
 
113
- Geocoder will print warnings if you exceed the rate limit for your geocoding service. Some services — Google notably — 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:
139
+ So, be careful.
114
140
 
115
- rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
141
+ ### Use Outside of Rails
116
142
 
117
- ### Avoiding Unnecessary API Requests
143
+ 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:
118
144
 
119
- 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:
145
+ extend Geocoder::Model::ActiveRecord
120
146
 
121
- * an address is present
122
- * the address has been changed since last save (or it has never been saved)
123
147
 
124
- The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
148
+ Geospatial Database Queries
149
+ ---------------------------
125
150
 
126
- after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
151
+ ### For ActiveRecord models:
152
+
153
+ To find objects by location, use the following scopes:
154
+
155
+ Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
156
+ Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
157
+ Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
158
+ Venue.geocoded # venues with coordinates
159
+ Venue.not_geocoded # venues without coordinates
160
+
161
+ With geocoded objects you can do things like this:
162
+
163
+ if obj.geocoded?
164
+ obj.nearbys(30) # other objects within 30 miles
165
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
166
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
167
+ end
168
+
169
+ ### For MongoDB-backed models:
127
170
 
171
+ Please do not use Geocoder's `near` method. Instead use MongoDB's built-in [geospatial query language](https://docs.mongodb.org/manual/reference/command/geoNear/), which is faster. Mongoid also provides [a DSL](http://mongoid.github.io/en/mongoid/docs/querying.html#geo_near) for geospatial queries.
128
172
 
129
- Request Geocoding by IP Address
130
- -------------------------------
173
+
174
+ Geocoding HTTP Requests
175
+ -----------------------
131
176
 
132
177
  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:
133
178
 
@@ -136,164 +181,181 @@ Geocoder adds `location` and `safe_location` methods to the standard `Rack::Requ
136
181
 
137
182
  **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).
138
183
 
139
- Note that these methods will usually return `nil` in your test and development environments because things like "localhost" and "0.0.0.0" are not an Internet IP addresses.
184
+ 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.
140
185
 
141
- See _Advanced Geocoding_ below for more information about `Geocoder::Result` objects.
142
186
 
187
+ Geocoding Service ("Lookup") Configuration
188
+ ------------------------------------------
143
189
 
144
- Location-Aware Database Queries
145
- -------------------------------
190
+ 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](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) for details on specific geocoding services (not all settings are supported by all services).
146
191
 
147
- ### For Mongo-backed models:
192
+ To create a Rails initializer with sample configuration:
148
193
 
149
- Please use MongoDB's [geospatial query language](https://docs.mongodb.org/manual/reference/command/geoNear/). Mongoid also provides [a DSL](http://mongoid.github.io/en/mongoid/docs/querying.html#geo_near) for doing near queries.
194
+ rails generate geocoder:config
150
195
 
151
- ### For ActiveRecord models:
196
+ Some common options are:
152
197
 
153
- To find objects by location, use the following scopes:
198
+ # config/initializers/geocoder.rb
199
+ Geocoder.configure(
154
200
 
155
- Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
156
- Venue.near([40.71, -100.23], 20) # venues within 20 miles of a point
157
- Venue.near([40.71, -100.23], 20, :units => :km)
158
- # venues within 20 kilometres of a point
159
- Venue.geocoded # venues with coordinates
160
- Venue.not_geocoded # venues without coordinates
201
+ # street address geocoding service (default :nominatim)
202
+ lookup: :yandex,
161
203
 
162
- by default, objects are ordered by distance. To remove the ORDER BY clause use the following:
204
+ # IP address geocoding service (default :ipinfo_io)
205
+ ip_lookup: :maxmind,
163
206
 
164
- Venue.near('Omaha', 20, :order => false)
207
+ # to use an API key:
208
+ api_key: "...",
165
209
 
166
- With geocoded objects you can do things like this:
210
+ # geocoding service request timeout, in seconds (default 3):
211
+ timeout: 5,
167
212
 
168
- if obj.geocoded?
169
- obj.nearbys(30) # other objects within 30 miles
170
- obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
171
- obj.bearing_to("Paris, France") # direction from object to arbitrary point
172
- end
213
+ # set default units to kilometers:
214
+ units: :km,
173
215
 
174
- Some utility methods are also available:
216
+ # caching (see [below](#caching) for details):
217
+ cache: Redis.new,
218
+ cache_prefix: "..."
175
219
 
176
- # look up coordinates of some location (like searching Google Maps)
177
- Geocoder.coordinates("25 Main St, Cooperstown, NY")
178
- => [42.700149, -74.922767]
220
+ )
179
221
 
180
- # distance between Eiffel Tower and Empire State Building
181
- Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
182
- => 3619.77359999382 # in configured units (default miles)
222
+ Please see [`lib/geocoder/configuration.rb`](https://github.com/alexreisner/geocoder/blob/master/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:
183
223
 
184
- # find the geographic center (aka center of gravity) of objects or points
185
- Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
186
- => [35.14968, -90.048929]
224
+ # with Google:
225
+ Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
187
226
 
188
- Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
227
+ Please see the [source code for each lookup](https://github.com/alexreisner/geocoder/tree/master/lib/geocoder/lookups) 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:
189
228
 
229
+ # Nominatim's `countrycodes` parameter:
230
+ Geocoder.search("Rome", params: {countrycodes: "us,ca"})
190
231
 
191
- Distance and Bearing
192
- --------------------
232
+ # Google's `region` parameter:
233
+ Geocoder.search("Rome", params: {region: "..."})
193
234
 
194
- When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
235
+ ### Configuring Multiple Services
195
236
 
196
- * `obj.distance` - number of miles from the search point to this object
197
- * `obj.bearing` - direction from the search point to this object
237
+ You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:
198
238
 
199
- Results are automatically sorted by distance from the search point, closest to farthest. Bearing is given as a number of clockwise degrees from due north, for example:
239
+ Geocoder.configure(
200
240
 
201
- * `0` - due north
202
- * `180` - due south
203
- * `90` - due east
204
- * `270` - due west
205
- * `230.1` - southwest
206
- * `359.9` - almost due north
241
+ timeout: 2,
242
+ cache: Redis.new,
207
243
 
208
- You can convert these numbers to compass point names by using the utility method provided:
244
+ yandex: {
245
+ api_key: "...",
246
+ timeout: 5
247
+ },
209
248
 
210
- Geocoder::Calculations.compass_point(355) # => "N"
211
- Geocoder::Calculations.compass_point(45) # => "NE"
212
- Geocoder::Calculations.compass_point(208) # => "SW"
249
+ baidu: {
250
+ api_key: "..."
251
+ },
213
252
 
214
- _Note: when using SQLite `distance` and `bearing` values are provided for interface consistency only. They are not very accurate._
253
+ maxmind: {
254
+ api_key: "...",
255
+ service: :omni
256
+ }
215
257
 
216
- To calculate accurate distance and bearing with SQLite or MongoDB:
258
+ )
217
259
 
218
- obj.distance_to([43.9,-98.6]) # distance from obj to point
219
- obj.bearing_to([43.9,-98.6]) # bearing from obj to point
220
- obj.bearing_from(obj2) # bearing from obj2 to obj
260
+ Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.
221
261
 
222
- 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).
223
262
 
263
+ Performance and Optimization
264
+ ----------------------------
224
265
 
225
- Model Configuration
226
- -------------------
266
+ ### Database Indices
227
267
 
228
- You are not stuck with using the `latitude` and `longitude` database column names (with ActiveRecord) or the `coordinates` array (Mongo) for storing coordinates. For example:
268
+ 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:
229
269
 
230
- geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
231
- geocoded_by :address, :coordinates => :coords # MongoDB
270
+ add_index :table, [:latitude, :longitude]
232
271
 
233
- The `address` method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
272
+ 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:
234
273
 
235
- * "714 Green St, Big Town, MO"
236
- * "Eiffel Tower, Paris, FR"
237
- * "Paris, TX, US"
274
+ include Geocoder::Model::Mongoid
275
+ geocoded_by :address, skip_index: true
238
276
 
239
- If your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
277
+ ### Avoiding Unnecessary API Requests
240
278
 
241
- geocoded_by :address
279
+ 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:
242
280
 
243
- def address
244
- [street, city, state, country].compact.join(', ')
245
- end
281
+ * an address is present
282
+ * the address has been changed since last save (or it has never been saved)
246
283
 
247
- For reverse geocoding, you can also specify an alternate name attribute where the address will be stored. For example:
284
+ The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
248
285
 
249
- reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
250
- reverse_geocoded_by :coordinates, :address => :loc # MongoDB
286
+ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
251
287
 
252
- You can also configure a specific lookup for your model which will override the globally-configured lookup. For example:
288
+ ### Caching
253
289
 
254
- geocoded_by :address, :lookup => :yandex
290
+ 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:
255
291
 
256
- You can also specify a proc if you want to choose a lookup based on a specific property of an object. For example, you can use specialized lookups for different regions:
292
+ Geocoder.configure(cache: Redis.new)
257
293
 
258
- geocoded_by :address, :lookup => lambda{ |obj| obj.geocoder_lookup }
294
+ This example uses Redis, but the cache store can be any object that supports these methods:
259
295
 
260
- def geocoder_lookup
261
- if country_code == "RU"
262
- :yandex
263
- elsif country_code == "CN"
264
- :baidu
265
- else
266
- :google
267
- end
268
- end
296
+ * `store#[](key)` or `#get` or `#read` - retrieves a value
297
+ * `store#[]=(key, value)` or `#set` or `#write` - stores a value
298
+ * `store#del(url)` - deletes a value
299
+ * `store#keys` - (Optional) Returns array of keys. Used if you wish to expire the entire cache (see below).
300
+
301
+ 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).
269
302
 
303
+ You can also set a custom prefix to be used for cache keys:
270
304
 
271
- Advanced Querying
272
- -----------------
305
+ Geocoder.configure(cache_prefix: "...")
306
+
307
+ By default the prefix is `geocoder:`
308
+
309
+ If you need to expire cached content:
310
+
311
+ Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
312
+ Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
313
+ Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Google Lookup
314
+ # expire all cached results for all Lookups.
315
+ # Be aware that this methods spawns a new Lookup object for each Service
316
+ Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
317
+
318
+ 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.
273
319
 
274
- When querying for objects (if you're using ActiveRecord) you can also look within a square rather than a radius (circle) by using the `within_bounding_box` scope:
320
+ For an example of a cache store with URL expiry, please see examples/autoexpire_cache.rb
275
321
 
276
- distance = 20
277
- center_point = [40.71, 100.23]
278
- box = Geocoder::Calculations.bounding_box(center_point, distance)
279
- Venue.within_bounding_box(box)
322
+ _Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
280
323
 
281
- This can also dramatically improve query performance, especially when used in conjunction with indexes on the latitude/longitude columns. Note, however, that returned results do not include `distance` and `bearing` attributes. Also note that `#near` performs both bounding box and radius queries for speed.
282
324
 
283
- You can also specify a minimum radius (if you're using ActiveRecord and not Sqlite) to constrain the
284
- lower bound (ie. think of a donut, or ring) by using the `:min_radius` option:
325
+ Advanced Model Configuration
326
+ ----------------------------
285
327
 
286
- box = Geocoder::Calculations.bounding_box(center_point, distance, :min_radius => 10.5)
328
+ You are not stuck with the `latitude` and `longitude` database column names (with ActiveRecord) or the `coordinates` array (Mongo) for storing coordinates. For example:
287
329
 
288
- With ActiveRecord, you can specify alternate latitude and longitude column names for a geocoded model (useful if you store multiple sets of coordinates for each object):
330
+ geocoded_by :address, latitude: :lat, longitude: :lon # ActiveRecord
331
+ geocoded_by :address, coordinates: :coords # MongoDB
289
332
 
290
- Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
333
+ For reverse geocoding, you can specify the attribute where the address will be stored. For example:
334
+
335
+ reverse_geocoded_by :latitude, :longitude, address: :loc # ActiveRecord
336
+ reverse_geocoded_by :coordinates, address: :street_address # MongoDB
337
+
338
+ To specify geocoding parameters in your model:
339
+
340
+ geocoded_by :address, params: {region: "..."}
341
+
342
+ 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:
343
+
344
+ geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
291
345
 
346
+ def geocoder_lookup
347
+ if country_code == "RU"
348
+ :yandex
349
+ elsif country_code == "CN"
350
+ :baidu
351
+ else
352
+ :nominatim
353
+ end
354
+ end
292
355
 
293
- Advanced Geocoding
294
- ------------------
356
+ ### Custom Result Handling
295
357
 
296
- So far we have looked at shortcuts for assigning geocoding results to object attributes. However, if you need to do something fancy, you can skip the auto-assignment by providing a block (takes the object to be geocoded and an array of `Geocoder::Result` objects) in which you handle the parsed geocoding result any way you like, for example:
358
+ 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:
297
359
 
298
360
  reverse_geocoded_by :latitude, :longitude do |obj,results|
299
361
  if geo = results.first
@@ -317,677 +379,135 @@ Every `Geocoder::Result` object, `result`, provides the following data:
317
379
  * `result.country` - string
318
380
  * `result.country_code` - string
319
381
 
320
- If you're familiar with the results returned by the geocoding service you're using you can access even more data (call the `#data` method of any Geocoder::Result object to get the full parsed response), but you'll need to be familiar with the particular `Geocoder::Result` object you're using and the structure of your geocoding service's responses. (See below for links to geocoding service documentation.)
321
-
322
-
323
- Geocoding Service ("Lookup") Configuration
324
- ------------------------------------------
325
-
326
- Geocoder supports a variety of street and IP address geocoding services. The default lookups are `:google` for street addresses and `:freegeoip` for IP addresses. Please see the listing and comparison below for details on specific geocoding services (not all settings are supported by all services).
327
-
328
- To create a Rails initializer with an example configuration:
329
-
330
- rails generate geocoder:config
331
-
332
- Some common configuration options are:
333
-
334
- # config/initializers/geocoder.rb
335
- Geocoder.configure(
336
-
337
- # geocoding service (see below for supported options):
338
- :lookup => :yandex,
339
-
340
- # IP address geocoding service (see below for supported options):
341
- :ip_lookup => :maxmind,
342
-
343
- # to use an API key:
344
- :api_key => "...",
345
-
346
- # geocoding service request timeout, in seconds (default 3):
347
- :timeout => 5,
348
-
349
- # set default units to kilometers:
350
- :units => :km,
351
-
352
- # caching (see below for details):
353
- :cache => Redis.new,
354
- :cache_prefix => "..."
355
-
356
- )
357
-
358
- Please see `lib/geocoder/configuration.rb` for a complete list of configuration options. Additionally, some lookups have their own configuration options, some of which are directly supported by Geocoder. For example, to specify a value for Google's `bounds` parameter:
359
-
360
- # with Google:
361
- Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])
362
-
363
- Please see the [source code for each lookup](https://github.com/alexreisner/geocoder/tree/master/lib/geocoder/lookups) to learn about directly supported parameters. Parameters which are not directly supported can be specified using the `:params` option, by which you can pass arbitrary parameters to any geocoding service. For example, to use Nominatim's `countrycodes` parameter:
364
-
365
- # with Nominatim:
366
- Geocoder.search("Paris", :params => {:countrycodes => "gb,de,fr,es,us"})
367
-
368
- Or, to search within a particular region with Google:
369
-
370
- Geocoder.search("...", :params => {:region => "..."})
371
-
372
- You can also configure multiple geocoding services at once, like this:
373
-
374
- Geocoder.configure(
375
-
376
- :timeout => 2,
377
- :cache => Redis.new,
378
-
379
- :yandex => {
380
- :api_key => "...",
381
- :timeout => 5
382
- },
383
-
384
- :baidu => {
385
- :api_key => "..."
386
- },
387
-
388
- :maxmind => {
389
- :api_key => "...",
390
- :service => :omni
391
- }
392
-
393
- )
394
-
395
- The above combines global and service-specific options and could be useful if you specify different geocoding services for different models or under different conditions. Lookup-specific settings override global settings. In the above example, the timeout for all lookups would be 2 seconds, except for Yandex which would be 5.
396
-
397
-
398
- ### Street Address Services
399
-
400
- The following is a comparison of the supported geocoding APIs. The "Limitations" listed for each are a very brief and incomplete summary of some special limitations beyond basic data source attribution. Please read the official Terms of Service for a service before using it.
382
+ 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](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) for links to documentation for all geocoding services.
401
383
 
402
- #### Google (`:google`)
384
+ ### Forward and Reverse Geocoding in the Same Model
403
385
 
404
- * **API key**: optional, but quota is higher if key is used (use of key requires HTTPS so be sure to set: `:use_https => true` in `Geocoder.configure`)
405
- * **Key signup**: https://console.developers.google.com/flows/enableapi?apiid=geocoding_backend&keyType=SERVER_SIDE
406
- * **Quota**: 2,500 requests/24 hrs, 5 requests/second
407
- * **Region**: world
408
- * **SSL support**: yes (required if key is used)
409
- * **Languages**: see https://developers.google.com/maps/faq#languagesupport
410
- * **Extra options**: `:bounds` - pass SW and NE coordinates as an array of two arrays to bias results towards a viewport
411
- * **Documentation**: https://developers.google.com/maps/documentation/geocoding/intro
412
- * **Terms of Service**: http://code.google.com/apis/maps/terms.html#section_10_12
413
- * **Limitations**: "You must not use or display the Content without a corresponding Google map, unless you are explicitly permitted to do so in the Maps APIs Documentation, or through written permission from Google." "You must not pre-fetch, cache, or store any Content, except that you may store: (i) limited amounts of Content for the purpose of improving the performance of your Maps API Implementation..."
414
-
415
- #### Google Maps API for Work (`:google_premier`)
416
-
417
- Similar to `:google`, with the following differences:
418
-
419
- * **API key**: required, plus client and channel (set `Geocoder.configure(:lookup => :google_premier, :api_key => [key, client, channel])`)
420
- * **Key signup**: https://developers.google.com/maps/documentation/business/
421
- * **Quota**: 100,000 requests/24 hrs, 10 requests/second
422
-
423
- #### Google Places Details (`:google_places_details`)
424
-
425
- The [Google Places Details API](https://developers.google.com/places/documentation/details) is not, strictly speaking, a geocoding service. It accepts a Google `place_id` and returns address information, ratings and reviews. A `place_id` can be obtained from the Google Places Search lookup (`:google_places_search`) and should be passed to Geocoder as the first search argument: `Geocoder.search("ChIJhRwB-yFawokR5Phil-QQ3zM", lookup: :google_places_details)`.
426
-
427
- * **API key**: required
428
- * **Key signup**: https://code.google.com/apis/console/
429
- * **Quota**: 1,000 request/day, 100,000 after credit card authentication
430
- * **Region**: world
431
- * **SSL support**: yes
432
- * **Languages**: ar, eu, bg, bn, ca, cs, da, de, el, en, en-AU, en-GB, es, eu, fa, fi, fil, fr, gl, gu, hi, hr, hu, id, it, iw, ja, kn, ko, lt, lv, ml, mr, nl, no, pl, pt, pt-BR, pt-PT, ro, ru, sk, sl, sr, sv, tl, ta, te, th, tr, uk, vi, zh-CN, zh-TW (see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1)
433
- * **Documentation**: https://developers.google.com/places/documentation/details
434
- * **Terms of Service**: https://developers.google.com/places/policies
435
- * **Limitations**: "If your application displays Places API data on a page or view that does not also display a Google Map, you must show a "Powered by Google" logo with that data."
436
-
437
- #### Google Places Search (`:google_places_search`)
438
-
439
- The [Google Places Search API](https://developers.google.com/places/web-service/search) is the geocoding service of Google Places API. It returns very limited location data, but it also returns a `place_id` which can be used with Google Place Details to get more detailed information. For a comparison between this and the regular Google Geocoding API, see https://maps-apis.googleblog.com/2016/11/address-geocoding-in-google-maps-apis.html
440
-
441
- * Same specifications as Google Places Details (see above).
442
-
443
- #### Bing (`:bing`)
444
-
445
- * **API key**: required (set `Geocoder.configure(:lookup => :bing, :api_key => key)`)
446
- * **Key signup**: https://www.microsoft.com/maps/create-a-bing-maps-key.aspx
447
- * **Quota**: 50,0000 requests/day (Windows app), 125,000 requests/year (non-Windows app)
448
- * **Region**: world
449
- * **SSL support**: no
450
- * **Languages**: ?
451
- * **Documentation**: http://msdn.microsoft.com/en-us/library/ff701715.aspx
452
- * **Terms of Service**: http://www.microsoft.com/maps/product/terms.html
453
- * **Limitations**: No country codes or state names. Must be used on "public-facing, non-password protected web sites," "in conjunction with Bing Maps or an application that integrates Bing Maps."
454
-
455
- #### Nominatim (`:nominatim`)
456
-
457
- * **API key**: none
458
- * **Quota**: 1 request/second
459
- * **Region**: world
460
- * **SSL support**: no
461
- * **Languages**: ?
462
- * **Documentation**: http://wiki.openstreetmap.org/wiki/Nominatim
463
- * **Terms of Service**: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
464
- * **Limitations**: Please limit request rate to 1 per second and include your contact information in User-Agent headers (eg: `Geocoder.configure(:http_headers => { "User-Agent" => "your contact info" })`). [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://www.openstreetmap.org/copyright)
465
-
466
- #### LocationIQ (`:location_iq`)
467
-
468
- * **API key**: required
469
- * **Quota**: 6 request/second (30k req/day), then ability to purchase more
470
- * **Region**: world
471
- * **SSL support**: yes
472
- * **Languages**: ?
473
- * **Documentation**: http://locationiq.org/#docs
474
- * **Terms of Service**: https://unwiredlabs.com/tos
475
- * **Limitations**: [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://www.openstreetmap.org/copyright)
476
-
477
- #### OpenCageData (`:opencagedata`)
478
-
479
- * **API key**: required
480
- * **Key signup**: http://geocoder.opencagedata.com
481
- * **Quota**: 2500 requests / day, then ability to purchase more (free during beta)
482
- * **Region**: world
483
- * **SSL support**: yes
484
- * **Languages**: worldwide
485
- * **Documentation**: http://geocoder.opencagedata.com/api.html
486
- * **Limitations**: [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://www.openstreetmap.org/copyright)
487
-
488
- #### Yandex (`:yandex`)
489
-
490
- * **API key**: optional, but without it lookup is territorially limited
491
- * **Quota**: 25000 requests / day
492
- * **Region**: world with API key. Otherwise restricted to Russia, Ukraine, Belarus, Kazakhstan, Georgia, Abkhazia, South Ossetia, Armenia, Azerbaijan, Moldova, Turkmenistan, Tajikistan, Uzbekistan, Kyrgyzstan and Turkey
493
- * **SSL support**: HTTPS only
494
- * **Languages**: Russian, Belarusian, Ukrainian, English, Turkish (only for maps of Turkey)
495
- * **Documentation**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml
496
- * **Terms of Service**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml#rules
497
- * **Limitations**: ?
498
-
499
- #### Geocoder.ca (`:geocoder_ca`)
500
-
501
- * **API key**: none
502
- * **Quota**: ?
503
- * **Region**: US and Canada
504
- * **SSL support**: no
505
- * **Languages**: English
506
- * **Documentation**: ?
507
- * **Terms of Service**: http://geocoder.ca/?terms=1
508
- * **Limitations**: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
509
-
510
- #### Geocoder.us (`:geocoder_us`)
511
-
512
- * **API key**: HTTP Basic Auth
513
- * **Sign up**: http://geocoder.us/user/signup
514
- * **Quota**: You can purchase 20,000 credits at a time for $50
515
- * **Region**: US
516
- * **SSL support**: no
517
- * **Languages**: English
518
- * **Documentation**: http://geocoder.us/help/
519
- * **Terms of Service**: http://geocoder.us/terms.shtml
520
- * **Limitations**: ?
521
-
522
- #### Mapbox (`:mapbox`)
523
-
524
- * **API key**: required
525
- * **Dataset**: Uses `mapbox.places` dataset by default. Specify the `mapbox.places-permanent` dataset by setting: `Geocoder.configure(:mapbox => {:dataset => "mapbox.places-permanent"})`
526
- * **Key signup**: https://www.mapbox.com/pricing/
527
- * **Quota**: depends on plan
528
- * **Region**: complete coverage of US and Canada, partial coverage elsewhere (see for details: https://www.mapbox.com/developers/api/geocoding/#coverage)
529
- * **SSL support**: yes
530
- * **Languages**: English
531
- * **Documentation**: https://www.mapbox.com/developers/api/geocoding/
532
- * **Terms of Service**: https://www.mapbox.com/tos/
533
- * **Limitations**: For `mapbox.places` dataset, must be displayed on a Mapbox map; Cache results for up to 30 days. For `mapbox.places-permanent` dataset, depends on plan.
534
- * **Notes**: Currently in public beta.
535
-
536
- #### Mapquest (`:mapquest`)
537
-
538
- * **API key**: required
539
- * **Key signup**: https://developer.mapquest.com/plans
540
- * **Quota**: ?
541
- * **HTTP Headers**: when using the licensed API you can specify a referer like so:
542
- `Geocoder.configure(:http_headers => { "Referer" => "http://foo.com" })`
543
- * **Region**: world
544
- * **SSL support**: no
545
- * **Languages**: English
546
- * **Documentation**: http://www.mapquestapi.com/geocoding/
547
- * **Terms of Service**: http://info.mapquest.com/terms-of-use/
548
- * **Limitations**: ?
549
- * **Notes**: You can use the open (non-licensed) API by setting: `Geocoder.configure(:mapquest => {:open => true})` (defaults to licensed version)
550
-
551
- #### Ovi/Nokia (`:ovi`)
552
-
553
- * **API key**: not required, but performance restricted without it
554
- * **Quota**: ?
555
- * **Region**: world
556
- * **SSL support**: no
557
- * **Languages**: English
558
- * **Documentation**: http://api.maps.ovi.com/devguide/overview.html
559
- * **Terms of Service**: http://www.developer.nokia.com/Develop/Maps/TC.html
560
- * **Limitations**: ?
561
-
562
- #### Here/Nokia (`:here`)
563
-
564
- * **API key**: required (set `Geocoder.configure(:api_key => [app_id, app_code])`)
565
- * **Quota**: Depending on the API key
566
- * **Region**: world
567
- * **SSL support**: yes
568
- * **Languages**: The preferred language of address elements in the result. Language code must be provided according to RFC 4647 standard.
569
- * **Documentation**: http://developer.here.com/rest-apis/documentation/geocoder
570
- * **Terms of Service**: http://developer.here.com/faqs#l&t
571
- * **Limitations**: ?
572
-
573
- #### ESRI (`:esri`)
574
-
575
- * **API key**: optional (set `Geocoder.configure(:esri => {:api_key => ["client_id", "client_secret"]})`)
576
- * **Quota**: Required for some scenarios (see Terms of Service)
577
- * **Region**: world
578
- * **SSL support**: yes
579
- * **Languages**: English
580
- * **Documentation**: https://developers.arcgis.com/rest/geocode/api-reference/overview-world-geocoding-service.htm
581
- * **Terms of Service**: http://www.esri.com/legal/software-license
582
- * **Limitations**: Requires API key if results will be stored. Using API key will also remove rate limit.
583
- * **Notes**: You can specify which projection you want to use by setting, for example: `Geocoder.configure(:esri => {:outSR => 102100})`. If you will store results, set the flag and provide API key: `Geocoder.configure(:esri => {:api_key => ["client_id", "client_secret"], :for_storage => true})`. If you want to, you can also supply an ESRI token directly: `Geocoder.configure(:esri => {:token => Geocoder::EsriToken.new('TOKEN', Time.now + 1.day})`
584
-
585
- #### Mapzen (`:mapzen`)
586
-
587
- * **API key**: required
588
- * **Quota**: 6/sec, up to 30k per day, paid plan info at https://mapzen.com/documentation/search/api-keys-rate-limits/#rate-limits
589
- * **Region**: world
590
- * **SSL support**: yes
591
- * **Languages**: en
592
- * **Documentation**: https://mapzen.com/documentation/search/search/
593
- * **Terms of Service**: http://mapzen.com/terms
594
- * **Limitations**: ?
595
- * **Notes**: Mapzen is the primary author of Pelias and offers Pelias-as-a-service in free and paid versions https://mapzen.com/pelias.
596
-
597
- #### Pelias (`:pelias`)
598
-
599
- * **API key**: required
600
- * **Quota**: none (self-hosted service)
601
- * **Region**: world
602
- * **SSL support**: yes
603
- * **Languages**: en
604
- * **Documentation**: https://mapzen.com/documentation/search/search/
605
- * **Terms of Service**: http://mapzen.com/terms
606
- * **Limitations**: See terms
607
- * **Notes**: Configure your self-hosted pelias with the `endpoint` option: `Geocoder.configure(:lookup => :pelias, :api_key => 'your_api_key', :pelias => {:endpoint => 'self.hosted/pelias'})`. Defaults to `localhost`.
608
-
609
- #### Data Science Toolkit (`:dstk`)
610
-
611
- Data Science Toolkit provides an API whose response format is like Google's but which can be set up as a privately hosted service.
612
-
613
- * **API key**: none
614
- * **Quota**: None quota if you are self-hosting the service.
615
- * **Region**: world
616
- * **SSL support**: ?
617
- * **Languages**: en
618
- * **Documentation**: http://www.datasciencetoolkit.org/developerdocs
619
- * **Terms of Service**: http://www.datasciencetoolkit.org/developerdocs#googlestylegeocoder
620
- * **Limitations**: No reverse geocoding.
621
- * **Notes**: If you are hosting your own DSTK server you will need to configure the host name, eg: `Geocoder.configure(:lookup => :dstk, :dstk => {:host => "localhost:4567"})`.
622
-
623
- #### Baidu (`:baidu`)
624
-
625
- * **API key**: required
626
- * **Quota**: No quota limits for geocoding
627
- * **Region**: China
628
- * **SSL support**: no
629
- * **Languages**: Chinese (Simplified)
630
- * **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
631
- * **Terms of Service**: http://developer.baidu.com/map/law.htm
632
- * **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
633
- * **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu, :api_key => "your_api_key")`.
634
-
635
- #### Geocodio (`:geocodio`)
636
-
637
- * **API key**: required
638
- * **Quota**: 2,500 free requests/day then purchase $.001 for each, also has volume pricing and plans
639
- * **Region**: US
640
- * **SSL support**: yes
641
- * **Languages**: en
642
- * **Documentation**: http://geocod.io/docs
643
- * **Terms of Service**: http://geocod.io/terms-of-use
644
- * **Limitations**: No restrictions on use
645
-
646
- #### SmartyStreets (`:smarty_streets`)
647
-
648
- * **API key**: requires auth_id and auth_token (set `Geocoder.configure(:api_key => [id, token])`)
649
- * **Quota**: 10,000 free, 250/month then purchase at sliding scale.
650
- * **Region**: US
651
- * **SSL support**: yes (required)
652
- * **Languages**: en
653
- * **Documentation**: http://smartystreets.com/kb/liveaddress-api/rest-endpoint
654
- * **Terms of Service**: http://smartystreets.com/legal/terms-of-service
655
- * **Limitations**: No reverse geocoding.
656
-
657
-
658
- #### OKF Geocoder (`:okf`)
659
-
660
- * **API key**: none
661
- * **Quota**: none
662
- * **Region**: FI
663
- * **SSL support**: no
664
- * **Languages**: fi
665
- * **Documentation**: http://books.okf.fi/geocoder/_full/
666
- * **Terms of Service**: http://www.itella.fi/liitteet/palvelutjatuotteet/yhteystietopalvelut/Postinumeropalvelut-Palvelukuvausjakayttoehdot.pdf
667
- * **Limitations**: ?
668
-
669
- #### Geoportail.lu (`:geoportail_lu`)
670
-
671
- * **API key**: none
672
- * **Quota**: none
673
- * **Region**: LU
674
- * **SSL support**: yes
675
- * **Languages**: en
676
- * **Documentation**: http://wiki.geoportail.lu/doku.php?id=en:api
677
- * **Terms of Service**: http://wiki.geoportail.lu/doku.php?id=en:mcg_1
678
- * **Limitations**: ?
679
-
680
- #### PostcodeAnywhere Uk (`:postcode_anywhere_uk`)
681
-
682
- This uses the PostcodeAnywhere UK Geocode service, this will geocode any string from UK postcode, placename, point of interest or location.
683
-
684
- * **API key**: required
685
- * **Quota**: Dependant on service plan?
686
- * **Region**: UK
687
- * **SSL support**: yes
688
- * **Languages**: English
689
- * **Documentation**: [http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/](http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/)
690
- * **Terms of Service**: ?
691
- * **Limitations**: ?
692
- * **Notes**: To use PostcodeAnywhere you must include an API key: `Geocoder.configure(:lookup => :postcode_anywhere_uk, :api_key => 'your_api_key')`.
693
-
694
- #### LatLon.io (`:latlon`)
695
-
696
- * **API key**: required
697
- * **Quota**: Depends on the user's plan (free and paid plans available)
698
- * **Region**: US
699
- * **SSL support**: yes
700
- * **Languages**: en
701
- * **Documentation**: https://latlon.io/documentation
702
- * **Terms of Service**: ?
703
- * **Limitations**: No restrictions on use
704
-
705
- #### Base Adresse Nationale FR (`:ban_data_gouv_fr`)
706
-
707
- * **API key**: none
708
- * **Quota**: none
709
- * **Region**: FR
710
- * **SSL support**: yes
711
- * **Languages**: en / fr
712
- * **Documentation**: https://adresse.data.gouv.fr/api/ (in french)
713
- * **Terms of Service**: https://adresse.data.gouv.fr/faq/ (in french)
714
- * **Limitations**: [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://openstreetmap.fr/ban)
715
-
716
- ### IP Address Services
717
-
718
- #### FreeGeoIP (`:freegeoip`)
719
-
720
- * **API key**: none
721
- * **Quota**: 10000 requests per hour. After reaching the hourly quota, all of your requests will result in HTTP 403 (Forbidden) until it clears up on the next roll over.
722
- * **Region**: world
723
- * **SSL support**: no
724
- * **Languages**: English
725
- * **Documentation**: http://github.com/fiorix/freegeoip/blob/master/README.md
726
- * **Terms of Service**: ?
727
- * **Limitations**: ?
728
- * **Notes**: If you are [running your own local instance of the FreeGeoIP service](https://github.com/fiorix/freegeoip) you can configure the host like this: `Geocoder.configure(freegeoip: {host: "..."})`.
729
-
730
- #### Pointpin (`:pointpin`)
731
-
732
- * **API key**: required
733
- * **Quota**: 50,000/mo for €9 through 1m/mo for €49
734
- * **Region**: world
735
- * **SSL support**: yes
736
- * **Languages**: English
737
- * **Documentation**: https://pointp.in/docs/get-started
738
- * **Terms of Service**: https://pointp.in/terms
739
- * **Limitations**: ?
740
- * **Notes**: To use Pointpin set `Geocoder.configure(:ip_lookup => :pointpin, :api_key => "your_pointpin_api_key")`.
741
-
742
- #### Telize (`:telize`)
743
-
744
- * **API key**: required
745
- * **Quota**: 1,000/day for $7/mo through 100,000/day for $100/mo
746
- * **Region**: world
747
- * **SSL support**: yes
748
- * **Languages**: English
749
- * **Documentation**: https://market.mashape.com/fcambus/telize
750
- * **Terms of Service**: ?
751
- * **Limitations**: ?
752
- * **Notes**: To use Telize set `Geocoder.configure(:ip_lookup => :telize, :api_key => "your_api_key")`.
753
-
754
- #### MaxMind Legacy Web Services (`:maxmind`)
755
-
756
- * **API key**: required
757
- * **Quota**: Request Packs can be purchased
758
- * **Region**: world
759
- * **SSL support**: yes
760
- * **Languages**: English
761
- * **Documentation**: http://dev.maxmind.com/geoip/legacy/web-services/
762
- * **Terms of Service**: ?
763
- * **Limitations**: ?
764
- * **Notes**: You must specify which MaxMind service you are using in your configuration. For example: `Geocoder.configure(:maxmind => {:service => :omni})`.
765
-
766
- #### Baidu IP (`:baidu_ip`)
767
-
768
- * **API key**: required
769
- * **Quota**: No quota limits for geocoding
770
- * **Region**: China
771
- * **SSL support**: no
772
- * **Languages**: Chinese (Simplified)
773
- * **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
774
- * **Terms of Service**: http://developer.baidu.com/map/law.htm
775
- * **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
776
- * **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu_ip, :api_key => "your_api_key")`.
777
-
778
- #### MaxMind GeoIP2 Precision Web Services (`:maxmind_geoip2`)
779
-
780
- * **API key**: required
781
- * **Quota**: Request Packs can be purchased
782
- * **Region**: world
783
- * **SSL support**: yes
784
- * **Languages**: English
785
- * **Documentation**: http://dev.maxmind.com/geoip/geoip2/web-services/
786
- * **Terms of Service**: ?
787
- * **Limitations**: ?
788
- * **Notes**: You must specify which MaxMind service you are using in your configuration, and also basic authentication. For example: `Geocoder.configure(:maxmind_geoip2 => {:service => :country, :basic_auth => {:user => '', :password => ''}})`.
789
-
790
- #### IPInfo.io (`:ipinfo_io`)
791
-
792
- * **API key**: optional - see http://ipinfo.io/pricing
793
- * **Quota**: 1,000/day - more with api key
794
- * **Region**: world
795
- * **SSL support**: no (not without access key - see http://ipinfo.io/pricing)
796
- * **Languages**: English
797
- * **Documentation**: http://ipinfo.io/developers
798
- * **Terms of Service**: http://ipinfo.io/developers
799
-
800
- #### IP-API.com (`:ipapi_com`)
801
-
802
- * **API key**: optional - see http://ip-api.com/docs/#usage_limits
803
- * **Quota**: 150/minute - unlimited with api key
804
- * **Region**: world
805
- * **SSL support**: no (not without access key - see https://signup.ip-api.com/)
806
- * **Languages**: English
807
- * **Documentation**: http://ip-api.com/docs/
808
- * **Terms of Service**: https://signup.ip-api.com/terms
809
-
810
- ### IP Address Local Database Services
811
-
812
- #### MaxMind Local (`:maxmind_local`) - EXPERIMENTAL
813
-
814
- This lookup provides methods for geocoding IP addresses without making a call to a remote API (improves speed and availability). It works, but support is new and should not be considered production-ready. Please [report any bugs](https://github.com/alexreisner/geocoder/issues) you encounter.
815
-
816
- * **API key**: none (requires the GeoLite City database which can be downloaded from [MaxMind](http://dev.maxmind.com/geoip/legacy/geolite/))
817
- * **Quota**: none
818
- * **Region**: world
819
- * **SSL support**: N/A
820
- * **Languages**: English
821
- * **Documentation**: http://www.maxmind.com/en/city
822
- * **Terms of Service**: ?
823
- * **Limitations**: ?
824
- * **Notes**: There are two supported formats for MaxMind local data: binary file, and CSV file imported into an SQL database. **You must download a database from MaxMind and set either the `:file` or `:package` configuration option for local lookups to work.**
825
-
826
- **To use a binary file** you must add the *geoip* (or *jgeoip* for JRuby) gem to your Gemfile or have it installed in your system, and specify the path of the MaxMind database in your configuration. For example:
827
-
828
- Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {file: File.join('folder', 'GeoLiteCity.dat')})
829
-
830
- **To use a CSV file** you must import it into an SQL database. The GeoLite *City* and *Country* packages are supported. Configure like so:
831
-
832
- Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {package: :city})
833
-
834
- You can generate ActiveRecord migrations and download and import data via provided rake tasks:
835
-
836
- # generate migration to create tables
837
- rails generate geocoder:maxmind:geolite_city
838
-
839
- # download, unpack, and import data
840
- rake geocoder:maxmind:geolite:load PACKAGE=city
841
-
842
- You can replace `city` with `country` in any of the above tasks, generators, and configurations.
843
-
844
- #### GeoLite2 (`:geoip2`)
845
-
846
- This lookup provides methods for geocoding IP addresses without making a call to a remote API (improves speed and availability). It works, but support is new and should not be considered production-ready. Please [report any bugs](https://github.com/alexreisner/geocoder/issues) you encounter.
847
-
848
- * **API key**: none (requires a GeoIP2 or free GeoLite2 City or Country binary database which can be downloaded from [MaxMind](http://dev.maxmind.com/geoip/geoip2/))
849
- * **Quota**: none
850
- * **Region**: world
851
- * **SSL support**: N/A
852
- * **Languages**: English
853
- * **Documentation**: http://www.maxmind.com/en/city
854
- * **Terms of Service**: ?
855
- * **Limitations**: ?
856
- * **Notes**: **You must download a binary database file from MaxMind and set the `:file` configuration option.** The CSV format databases are not yet supported since they are still in alpha stage. Set the path to the database file in your configuration:
386
+ 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:
857
387
 
858
- Geocoder.configure(
859
- ip_lookup: :geoip2,
860
- geoip2: {
861
- file: File.join('folder', 'GeoLite2-City.mmdb')
862
- }
863
- )
864
-
865
- You must add either the *[hive_geoip2](https://rubygems.org/gems/hive_geoip2)* gem (native extension that relies on libmaxminddb) or the *[maxminddb](http://rubygems.org/gems/maxminddb)* gem (pure Ruby implementation) to your Gemfile or have it installed in your system. The pure Ruby gem (maxminddb) will be used by default. To use `hive_geoip2`:
866
-
867
- Geocoder.configure(
868
- ip_lookup: :geoip2,
869
- geoip2: {
870
- lib: 'hive_geoip2',
871
- file: File.join('folder', 'GeoLite2-City.mmdb')
872
- }
873
- )
388
+ * one for storing the fetched address (when reverse geocoding)
389
+ * one for providing an address to use when fetching coordinates (forward geocoding)
874
390
 
875
- Caching
876
- -------
391
+ For example:
877
392
 
878
- 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:
393
+ class Venue
879
394
 
880
- Geocoder.configure(:cache => Redis.new)
395
+ # build an address from street, city, and state attributes
396
+ geocoded_by :address_from_components
881
397
 
882
- This example uses Redis, but the cache store can be any object that supports these methods:
398
+ # store the fetched address in the full_address attribute
399
+ reverse_geocoded_by :latitude, :longitude, address: :full_address
400
+ end
883
401
 
884
- * `store#[](key)` or `#get` or `#read` - retrieves a value
885
- * `store#[]=(key, value)` or `#set` or `#write` - stores a value
886
- * `store#del(url)` - deletes a value
402
+ 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:
887
403
 
888
- 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).
404
+ class Venue
405
+ geocoded_by :address,
406
+ latitude: :fetched_latitude,
407
+ longitude: :fetched_longitude
408
+ reverse_geocoded_by :latitude, :longitude
409
+ end
889
410
 
890
- You can also set a custom prefix to be used for cache keys:
891
411
 
892
- Geocoder.configure(:cache_prefix => "...")
412
+ Advanced Database Queries
413
+ -------------------------
893
414
 
894
- By default the prefix is `geocoder:`
415
+ *The following apply to ActiveRecord only. For MongoDB, please use the built-in geospatial features.*
895
416
 
896
- If you need to expire cached content:
417
+ The default `near` search looks for objects within a circle. To search within a doughnut or ring use the `:min_radius` option:
897
418
 
898
- Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
899
- Geocoder::Lookup.get(:google).cache.expire("http://...") # expire cached result for a specific URL
900
- Geocoder::Lookup.get(:google).cache.expire(:all) # expire cached results for Google Lookup
901
- # expire all cached results for all Lookups.
902
- # Be aware that this methods spawns a new Lookup object for each Service
903
- Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
419
+ Venue.near("Austin, TX", 200, min_radius: 40)
904
420
 
905
- 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.
421
+ To search within a rectangle (note that results will *not* include `distance` and `bearing` attributes):
906
422
 
907
- For an example of a cache store with URL expiry, please see examples/autoexpire_cache.rb
423
+ sw_corner = [40.71, 100.23]
424
+ ne_corner = [36.12, 88.65]
425
+ Venue.within_bounding_box(sw_corner, ne_corner)
908
426
 
909
- _Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
427
+ 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:
910
428
 
429
+ Venue.near([40.71, 99.23], :effective_radius)
911
430
 
912
- Forward and Reverse Geocoding in the Same Model
913
- -----------------------------------------------
431
+ If you store multiple sets of coordinates for each object, you can specify latitude and longitude columns to use for a search:
914
432
 
915
- If you apply both forward and reverse geocoding functionality to the same model (i.e. users can supply an address or coordinates and you want to fill in whatever's missing), you will provide two address methods:
433
+ Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
916
434
 
917
- * one for storing the fetched address (reverse geocoding)
918
- * one for providing an address to use when fetching coordinates (forward geocoding)
435
+ ### Distance and Bearing
919
436
 
920
- For example:
437
+ When you run a geospatial query, the returned objects have two attributes added:
921
438
 
922
- class Venue
439
+ * `obj.distance` - number of miles from the search point to this object
440
+ * `obj.bearing` - direction from the search point to this object
923
441
 
924
- # build an address from street, city, and state attributes
925
- geocoded_by :address_from_components
442
+ 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:
926
443
 
927
- # store the fetched address in the full_address attribute
928
- reverse_geocoded_by :latitude, :longitude, :address => :full_address
929
- end
444
+ * `0` - due north
445
+ * `180` - due south
446
+ * `90` - due east
447
+ * `270` - due west
448
+ * `230.1` - southwest
449
+ * `359.9` - almost due north
930
450
 
931
- However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
451
+ You can convert these to compass point names via provided method:
932
452
 
933
- class Venue
453
+ Geocoder::Calculations.compass_point(355) # => "N"
454
+ Geocoder::Calculations.compass_point(45) # => "NE"
455
+ Geocoder::Calculations.compass_point(208) # => "SW"
934
456
 
935
- geocoded_by :address,
936
- :latitude => :fetched_latitude, # this will be overridden by the below
937
- :longitude => :fetched_longitude # same here
457
+ _Note: when running queries on SQLite, `distance` and `bearing` are provided for consistency only. They are not very accurate._
938
458
 
939
- reverse_geocoded_by :latitude, :longitude
940
- end
459
+ For more advanced geospatial querying, please see the [rgeo gem](https://github.com/rgeo/rgeo).
941
460
 
942
- We don't want ambiguity when doing distance calculations -- we need a single, authoritative source for coordinates!
943
461
 
944
- Once both forward and reverse geocoding has been applied, it is possible to call them sequentially.
462
+ Geospatial Calculations
463
+ -----------------------
945
464
 
946
- For example:
465
+ The `Geocoder::Calculations` module contains some useful methods:
947
466
 
948
- class Venue
467
+ # find the distance between two arbitrary points
468
+ Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
469
+ => 3619.77359999382 # in configured units (default miles)
949
470
 
950
- after_validation :geocode, :reverse_geocode
471
+ # find the geographic center (aka center of gravity) of objects or points
472
+ Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
473
+ => [35.14968, -90.048929]
951
474
 
952
- end
475
+ See [the code](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb) for more!
953
476
 
954
- For certain geolocation services such as Google's geolocation API, this may cause issues during subsequent updates to database records if the longitude and latitude coordinates cannot be associated with a known location address (on a large body of water for example). On subsequent callbacks the following call:
955
477
 
956
- after_validation :geocode
478
+ Batch Geocoding
479
+ ---------------
957
480
 
958
- will alter the longitude and latitude attributes based on the location field, which would be the closest known location to the original coordinates. In this case it is better to add conditions to each call, as not to override coordinates that do not have known location addresses associated with them.
481
+ 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:
959
482
 
960
- For example:
483
+ rake geocode:all CLASS=YourModel
961
484
 
962
- class Venue
485
+ If you need reverse geocoding instead, call the task with REVERSE=true:
963
486
 
964
- after_validation :reverse_geocode, :if => :has_coordinates
965
- after_validation :geocode, :if => :has_location, :unless => :has_coordinates
487
+ rake geocode:all CLASS=YourModel REVERSE=true
966
488
 
967
- end
489
+ 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:
968
490
 
969
- Use Outside of Rails
970
- --------------------
491
+ rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
971
492
 
972
- You can use Geocoder outside of Rails by calling the `Geocoder.search` method:
493
+ To avoid exceeding per-day limits you can add a `LIMIT` option. However, this will ignore the `BATCH` value, if provided.
973
494
 
974
- results = Geocoder.search("McCarren Park, Brooklyn, NY")
495
+ rake geocode:all CLASS=YourModel LIMIT=1000
975
496
 
976
- This returns an array of `Geocoder::Result` objects with all data provided by the geocoding service.
977
497
 
498
+ Testing
499
+ -------
978
500
 
979
- Testing Apps that Use Geocoder
980
- ------------------------------
501
+ 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`
981
502
 
982
- 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 and use the `:test` lookup. For example:
503
+ Geocoder.configure(lookup: :test, ip_lookup: :test)
983
504
 
984
- Geocoder.configure(:lookup => :test)
505
+ Add stubs to define the results that will be returned:
985
506
 
986
507
  Geocoder::Lookup::Test.add_stub(
987
508
  "New York, NY", [
988
509
  {
989
- 'latitude' => 40.7143528,
990
- 'longitude' => -74.0059731,
510
+ 'coordinates' => [40.7143528, -74.0059731],
991
511
  'address' => 'New York, NY, USA',
992
512
  'state' => 'New York',
993
513
  'state_code' => 'NY',
@@ -997,15 +517,12 @@ When writing tests for an app that uses Geocoder it may be useful to avoid netwo
997
517
  ]
998
518
  )
999
519
 
1000
- Now, any time Geocoder looks up "New York, NY" its results array will contain one result with the above attributes. You can also set a default stub, to be returned when no other stub is found for a given query:
1001
-
1002
- Geocoder.configure(:lookup => :test)
520
+ 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:
1003
521
 
1004
522
  Geocoder::Lookup::Test.set_default_stub(
1005
523
  [
1006
524
  {
1007
- 'latitude' => 40.7143528,
1008
- 'longitude' => -74.0059731,
525
+ 'coordinates' => [40.7143528, -74.0059731],
1009
526
  'address' => 'New York, NY, USA',
1010
527
  'state' => 'New York',
1011
528
  'state_code' => 'NY',
@@ -1017,8 +534,33 @@ Now, any time Geocoder looks up "New York, NY" its results array will contain on
1017
534
 
1018
535
  Notes:
1019
536
 
1020
- - Keys must be strings not symbols when calling `add_stub` or `set_default_stub`. For example `'latitude' =>` not `:latitude =>`.
537
+ - Keys must be strings (not symbols) when calling `add_stub` or `set_default_stub`. For example `'country' =>` not `:country =>`.
1021
538
  - To clear stubs (e.g. prior to another spec), use `Geocoder::Lookup::Test.reset`. This will clear all stubs _including the default stub_.
539
+ - 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.
540
+
541
+
542
+ Error Handling
543
+ --------------
544
+
545
+ 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:
546
+
547
+ Geocoder.configure(always_raise: [SocketError, Timeout::Error])
548
+
549
+ You can also do this to raise all exceptions:
550
+
551
+ Geocoder.configure(always_raise: :all)
552
+
553
+ The raise-able exceptions are:
554
+
555
+ SocketError
556
+ Timeout::Error
557
+ Geocoder::OverQueryLimitError
558
+ Geocoder::RequestDenied
559
+ Geocoder::InvalidRequest
560
+ Geocoder::InvalidApiKey
561
+ Geocoder::ServiceUnavailable
562
+
563
+ 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.
1022
564
 
1023
565
 
1024
566
  Command Line Interface
@@ -1034,63 +576,18 @@ When you install the Geocoder gem it adds a `geocode` command to your shell. You
1034
576
  State/province: Louisiana
1035
577
  Postal code: 70112
1036
578
  Country: United States
1037
- Google map: http://maps.google.com/maps?q=29.952211,-90.080563
579
+ Map: http://maps.google.com/maps?q=29.952211,-90.080563
1038
580
 
1039
581
  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.
1040
582
 
1041
- Numeric Data Types and Precision
1042
- --------------------------------
1043
-
1044
- Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
1045
-
1046
- A summary of the relationship between geographic precision and the number of decimal places in latitude and longitude degree values is available on [Wikipedia](http://en.wikipedia.org/wiki/Decimal_degrees#Accuracy). 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.
1047
-
1048
- Notes on MongoDB
1049
- ----------------
1050
-
1051
- ### The Near Method
1052
-
1053
- Mongo document classes (Mongoid and MongoMapper) have a built-in `near` scope, but since it only works two-dimensions Geocoder overrides it with its own spherical `near` method in geocoded classes.
1054
-
1055
- ### Latitude/Longitude Order
1056
-
1057
- Coordinates are generally printed and spoken as latitude, then longitude ([lat,lon]). Geocoder respects this convention and always expects method arguments to be given in [lat,lon] order. However, MongoDB requires that coordinates be stored in [lon,lat] order as per the GeoJSON spec (http://geojson.org/geojson-spec.html#positions), so internally they are stored "backwards." However, this does not affect order of arguments to methods when using Mongoid or MongoMapper.
1058
-
1059
- To access an object's coordinates in the conventional order, use the `to_coordinates` instance method provided by Geocoder. For example:
1060
-
1061
- obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
1062
-
1063
- Calling `obj.coordinates` directly returns the internal representation of the coordinates which, in the case of MongoDB, is probably the reverse of what you want:
1064
-
1065
- obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
1066
-
1067
- For consistency with the rest of Geocoder, always use the `to_coordinates` method instead.
1068
-
1069
- Notes on Non-Rails Frameworks
1070
- -----------------------------
1071
-
1072
- If you are using 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:
1073
-
1074
- extend Geocoder::Model::ActiveRecord
1075
-
1076
- Optimisation of Distance Queries
1077
- --------------------------------
1078
-
1079
- In MySQL and Postgres, the finding of objects near a given point is sped up by using a bounding box to limit the number of points over which a full distance calculation needs to be done.
1080
-
1081
- To take advantage of this optimisation, you need to add a composite index on latitude and longitude. In your Rails migration:
1082
-
1083
- add_index :table, [:latitude, :longitude]
1084
583
 
584
+ Technical Discussions
585
+ ---------------------
1085
586
 
1086
- Distance Queries in SQLite
1087
- --------------------------
587
+ ### Distance Queries in SQLite
1088
588
 
1089
589
  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.
1090
590
 
1091
-
1092
- ### Discussion
1093
-
1094
591
  There are few options for finding objects near a given point in SQLite without installing extensions:
1095
592
 
1096
593
  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.
@@ -1101,37 +598,11 @@ There are few options for finding objects near a given point in SQLite without i
1101
598
 
1102
599
  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.
1103
600
 
601
+ ### Numeric Data Types and Precision
1104
602
 
1105
- Tests
1106
- -----
1107
-
1108
- Geocoder comes with a test suite (just run `rake test`) that mocks ActiveRecord and is focused on testing the aspects of Geocoder that do not involve executing database queries. Geocoder uses many database engine-specific queries which must be tested against all supported databases (SQLite, MySQL, etc). Ideally this involves creating a full, working Rails application, and that seems beyond the scope of the included test suite. As such, I have created a separate repository which includes a full-blown Rails application and some utilities for easily running tests against multiple environments:
1109
-
1110
- http://github.com/alexreisner/geocoder_test
1111
-
1112
-
1113
- Error Handling
1114
- --------------
1115
-
1116
- 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:
1117
-
1118
- Geocoder.configure(:always_raise => [SocketError, Timeout::Error])
1119
-
1120
- You can also do this to raise all exceptions:
1121
-
1122
- Geocoder.configure(:always_raise => :all)
1123
-
1124
- The raise-able exceptions are:
1125
-
1126
- SocketError
1127
- Timeout::Error
1128
- Geocoder::OverQueryLimitError
1129
- Geocoder::RequestDenied
1130
- Geocoder::InvalidRequest
1131
- Geocoder::InvalidApiKey
1132
- Geocoder::ServiceUnavailable
603
+ Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
1133
604
 
1134
- 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.
605
+ A summary of the relationship between geographic precision and the number of decimal places in latitude and longitude degree values is available on [Wikipedia](http://en.wikipedia.org/wiki/Decimal_degrees#Accuracy). 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.
1135
606
 
1136
607
 
1137
608
  Troubleshooting
@@ -1167,24 +638,23 @@ For the most part, the speed of geocoding requests has little to do with the Geo
1167
638
 
1168
639
  Take a look at the server's raw response. You can do this by getting the request URL in an app console:
1169
640
 
1170
- Geocoder::Lookup.get(:google).query_url(Geocoder::Query.new("..."))
641
+ Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
1171
642
 
1172
- Replace `:google` 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.
643
+ 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.
1173
644
 
1174
645
  You can also fetch the response in the console:
1175
646
 
1176
- Geocoder::Lookup.get(:google).send(:fetch_raw_data, Geocoder::Query.new("..."))
647
+ Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
1177
648
 
1178
649
 
1179
- Reporting Issues
1180
- ----------------
1181
-
1182
- When reporting an issue, please list the version of Geocoder you are using and any relevant information about your application (Rails version, database type and version, etc). Also avoid vague language like "it doesn't work." Please describe as specifically as you can what behavior you are actually seeing (eg: an error message? a nil return value?).
650
+ Known Issues
651
+ ------------
1183
652
 
1184
- Please DO NOT use GitHub issues to ask questions about how to use Geocoder. Sites like [StackOverflow](http://www.stackoverflow.com/) are a better forum for such discussions.
653
+ ### Using `count` with Rails 4.1+
1185
654
 
655
+ Due to [a change in ActiveRecord's `count` method](https://github.com/rails/rails/pull/10710) 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.
1186
656
 
1187
- ### Known Issue
657
+ ### Using `near` with `includes`
1188
658
 
1189
659
  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).
1190
660
 
@@ -1192,7 +662,7 @@ Instead of using `includes` to reduce the number of database queries, try using
1192
662
 
1193
663
  # Pass a :select option to the near scope to get the columns you want.
1194
664
  # Instead of City.near(...).includes(:venues), try:
1195
- City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
665
+ City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
1196
666
 
1197
667
  # This preload call will normally trigger two queries regardless of the
1198
668
  # number of results; one query on hotels, and one query on administrators.
@@ -1201,6 +671,18 @@ Instead of using `includes` to reduce the number of database queries, try using
1201
671
 
1202
672
  If anyone has a more elegant solution to this problem I am very interested in seeing it.
1203
673
 
674
+ ### Using `near` with objects close to the 180th meridian
675
+
676
+ 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.
677
+
678
+
679
+ Reporting Issues
680
+ ----------------
681
+
682
+ When reporting an issue, please list the version of Geocoder you are using and any relevant information about your application (Rails version, database type and version, etc). Please describe as specifically as you can what behavior you are seeing (eg: an error message? a nil return value?).
683
+
684
+ Please DO NOT use GitHub issues to ask questions about how to use Geocoder. Sites like [StackOverflow](http://www.stackoverflow.com/) are a better forum for such discussions.
685
+
1204
686
 
1205
687
  Contributing
1206
688
  ------------
@@ -1219,4 +701,4 @@ For all contributions, please respect the following guidelines:
1219
701
  * If your pull request is merged, please do not ask for an immediate release of the gem. There are many factors contributing to when releases occur (remember that they affect thousands of apps with Geocoder in their Gemfiles). If necessary, please install from the Github source until the next official release.
1220
702
 
1221
703
 
1222
- Copyright (c) 2009-15 Alex Reisner, released under the MIT license
704
+ Copyright :copyright: 2009-2020 Alex Reisner, released under the MIT license.