Search code examples
ruby-on-railsruby-on-rails-3google-mapsgmaps4rails

Updating coordinates on changing model's address using Google-Maps-For-Rails


I have noticed with the Google Maps For Rails gems which otherwise works perfectly that when I change an address in the model field the coordinates are not automatically updated, even though the address field is updated and saved. I have created an before_save method that calls geocode.

before_save :update_location_coordinates # in model being mapped

protected 

def update_location_coordinates  
    place = Gmaps4rails.geocode(gmaps4rails_address).first  
    self.longitude, self.latitude = place[:lng], place[:lat] unless place.empty?  
rescue  
    nil  
end

This works but I am wondering if it is necessary as it seems like something that should be automatic in the gem. Am I missing something?

thanks...

PS geocode returns an array so I just took the first (best) guess


Solution

  • The refresh of the coordinates is a tricky process because of the gmaps4rails_address method. It's flexible so easy to use but the counterpart is it's not possible to know if the address really changed.

    That's why I give coders two different opportunities to fit their needs:

    1. If you don't care about performance, you could refresh the coordinates every time the model is saved (and then even if the address hasn't changed). See here: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Model-Customization.

    Change :check_process to false:

        acts_as_gmappable :check_process => false
    

    2. If you want to have full control over the process, set the gmaps boolean to false whenever you want the coordinates to be updated. It could be a hidden field in your form or a hook in your model checking the necessary fields.