Question

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

Was it helpful?

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.

OTHER TIPS

This is an economic way to solve the problem:

  1. add a column to the model - eg last_g4r_address
  2. add a before_validation function:

    def check_g4r_address self.gmaps = false if last_g4r_address != gmaps4rails_address self.last_g4r_address = gmaps4rails_address end

This way the geocoding is updated only if the address changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top