views:

22

answers:

2

I have this in my shop.rb:

def geocode_address
  if !address_geo.blank?
    geo=Geokit::Geocoders::MultiGeocoder.geocode(address_geo)
    errors.add(:address, "Could not Geocode address") if !geo.success
    self.lat, self.lng = geo.lat,geo.lng if geo.success
  end
end

# Checks whether this object has been geocoded or not. Returns the truth
def geocoded?
  lat? && lng?
end

And in my shops_controller.rb:

def update
@shop = Shop.find(params[:id])
if @shop.update_attributes(params[:shop])
  flash[:notice] = "Successfully saved."
  redirect_to shop_path(@shop, :type => @shop.shop_type)
else
  render :action => :edit
end
end

Now when the user first creates the entry, the address is geocoded, with latitude and longitude saved to the database.

But when the user updates the address, the latitude and longitude will not be geocoded anymore, and thus still using the old latitude and longitude which is the first save.

How do I write to have Rails re-geocode everytime an entry is update?

I can't depend on just the address because there is a bug in geokit that when I try to show multiple maps based on address, only the last one is shown.

I'm using geokit, Gmaps, Google Maps...

Thanks.

A: 

If the user changes their address can't you essentially handle it the same way as a new address? You basically have 2 new addresses you just need to link the newly created address with the user's account and everything should work.

Brian
No, it's not user's address. It's a shop's address. Let's say initially a shop's address is saved with info on city and country, the geocode will be based on that city and country. But when it's updated with a more precise address with street name, then geocode should update the longitude and latitude.
Victor
+1  A: 

I put this in my model:

  before_validation_on_update :geocode_address
Victor