Reputation: 177
I have searched high and low for a solution to this without luck, so I'm now posting here...
I'm using the Geocode gem on my RoR app.
This is the approach to geocoding multiple addresses on the same model in the docs and it doesn't work as it only geocodes the last method:
geocoded_by :start_address, latitude: :start_latitude, longitude: :start_longitude
geocoded_by :end_address, latitude: :end_latitude, longitude: :end_longitude
I have tried to write a custom method to solve this:
geocoded_by :geocode_user_addresses
after_validation :geocode
def geocode_user_addresses
home_address_joined = [home_address, city].compact.join(', ')
work_address_joined = [work_address, city].compact.join(', ')
home_coordinates = Geocoder.search(home_address_joined)
work_coordinates = Geocoder.search(work_address_joined)
self.home_latitude = home_coordinates.latitude
self.home_longitude = home_coordinates.longitude
self.work_latitude = work_coordinates.latitude
self.work_longitude = work_coordinates.longitude
end
That gives me this error when I try to geocode the addresses:
undefined method `latitude'
Any ideas on where to begin? There's a similar problem but no solution ended up being shared: Rails geocoder gem issues
Upvotes: 3
Views: 790
Reputation: 1136
Geocoder.search returns an array of location data.
In the sample provided, you can retrieve latitude and longitude with:
self.home_latitude = home_coordinates[0].geometry["location"]["lat"]
self.home_longitude = home_coordinates[0].geometry["location"]["lng"]
Upvotes: 2