Geocoder works with two addresses
rails 4.1.3 application with Geocoder gem has following attributes on model
t.decimal :origin_lon, :precision => 15, :scale => 10
t.decimal :origin_lat, :precision => 15, :scale => 10
t.point :origin_lonlat, :srid => 3857
t.decimal :destination_lon, :precision => 15, :scale => 10
t.decimal :destination_lat, :precision => 15, :scale => 10
t.point :destination_lonlat, :srid => 3857
The model is defined using
geocoded_by :origin, :latitude => :origin_lat, :longitude => :origin_lon
geocoded_by :destination, :latitude => :destination_lat, :longitude => :destination_lon
However, if I run the console:
Circuit.create(origin: 'avenue des Champs-Élysées, 90 Paris', destination: 'Place Mariejol, Antibes')
don't look, this is the Picasso Museum ...
only destination details are filled in. If the order of the instructions is geocoded_by
inverted and the server is restarted, the lineage data is filled. Thus, only one call is possible in this syntax geocoded_by
.
What syntax allows two simultaneous searches?
source to share
The problem geocoded_by
isgeocoder_init
, that contains a set of parameters , however geocoded_by :destination
clobbers geocoded_by :origin
.
def geocoder_init(options)
unless defined?(@geocoder_options)
@geocoder_options = {}
require "geocoder/stores/#{geocoder_file_name}"
include Geocoder::Store.const_get(geocoder_module_name)
end
@geocoder_options.merge! options
end
You can write your own ActiveRecord hook for geocoding:
class Circuit < ActiveRecord::Base
before_save :geocode_endpoints
private
def geocode_endpoints
if origin_changed?
geocoded = Geocoder.search(origin).first
if geocoded
self.origin_lat = geocoded.latitude
self.origin_lon = geocoded.longitude
end
end
# Repeat for destination
end
end
Take a look at the method geocode
to see how the stone does it, what errors it handles. etc. Unfortunately we cannot use do_lookup
it as it depends on the configured parameters instead of accepting the parameters.
source to share