Geocode multiple addresses in one model
I am trying to geocode 2 addresses in a model using a geocoder and I cannot get the gem to work the way I want. Here is the code I am applying to my model:
class Sender < ActiveRecord::Base
validates_presence_of :source_address
validates_presence_of :destination_address
geocoded_by :source_address, :latitude => :latitude1, :longitude => :longitude1
geocoded_by :destination_address, :latitude2 => :latitude2, :longitude2 => :longitude2
def update_coordinates
geocode
[latitude1, longitude1, latitude2, longitude2]
end
after_validation :geocode
Here is the code for views / senders / show.html.erb:
<%= @sender.latitude1 %>
<%= @sender.longitude1 %>
<%= @sender.latitude2 %>
<%= @sender.longitude2 %>
Result: 35.6894875 139.6917064 - Are you going to send me 2 address information?
Here is my js:
<script type="text/javascript">
function initialize() {
var source = new google.maps.LatLng(<%= @sender.latitude1 %>, <%= @sender.longitude1 %>);
var dest = new google.maps.LatLng(<%= @sender.latitude2 %>, <%= @sender.longitude2 %>);
var mapOptions = {
center: source,
zoom: 8
}
var mapOptions2 = {
center: dest,
zoom: 8
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var map2 = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions2);
var marker = new google.maps.Marker({
position:source,
map: map
});
var marker2 = new google.maps.Marker({
position:dest,
map: map2
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
source to share
The problem and solution are mentioned here .
Add the following before_save
and the appropriate method to your model to solve the problem. Don't forget to repeat some of the code for the second location (possibly the destination):
before_save :geocode_endpoints
private
#To enable Geocoder to works with multiple locations
def geocode_endpoints
if from_changed?
geocoded = Geocoder.search(loc1).first
if geocoded
self.latitude = geocoded.latitude
self.longitude = geocoded.longitude
end
end
# Repeat for destination
if to_changed?
geocoded = Geocoder.search(loc2).first
if geocoded
self.latitude2 = geocoded.latitude
self.longitude2 = geocoded.longitude
end
end
end
source to share
Rewrite
def function
...
end
as:
def update_coordinates
geocode
[latitude, longitude, latitude2, longitude2]
end
And:
geocoded_by :destination_address, :latitude => :latitude2, :longitude => :longitude2
You also don't need :latitude => :lat, :longitude => :lon
here:
geocoded_by :source_address, ...
Finally, the coordinates are selected automatically after confirming the entry. So you can do without update_coordinates
(or function
in your version) and arrange the view for the show action like this:
<%= @sender.latitude %>
<%= @sender.longitude %>
<%= @sender.latitude2 %>
<%= @sender.longitude2 %>
source to share