Geocode multiple addresses

I have searched high and low for a solution to this with no luck, so I am now posting here ...

I am using Geocode gem in my RoR application.

This is an approach to geocoding multiple addresses on the same model in documents, and it doesn't work as it only geocodes the latter method:

geocoded_by :start_address, latitude: :start_latitude, longitude: :start_longitude
geocoded_by :end_address, latitude: :end_latitude, longitude: :end_longitude

      

I tried to write my own method to solve this problem:

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

      

It gives me this error when I try to geocode addresses:

undefined method `latitude'

      

Any ideas on where to start? There's a similar problem, but no solution shared: Rails Geocoding Bump Issues

+3


source to share


1 answer


Geocoder.search returns an array of location data.

In the example provided, you can get the latitude and longitude with:



self.home_latitude = home_coordinates[0].geometry["location"]["lat"]

self.home_longitude = home_coordinates[0].geometry["location"]["lng"]

+2


source







All Articles