使用 Google-Maps-For-Rails 更新更改模型地址的坐标
我注意到 Google Maps For Rails gems 工作得很好,当我更改模型字段中的地址时,即使地址字段已更新并保存,坐标也不会自动更新。我创建了一个调用地理编码的 before_save 方法。
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
这是可行的,但我想知道是否有必要,因为它似乎应该在宝石中自动进行。我错过了什么吗?
谢谢...
PS geocode 返回一个数组,所以我只是采取了第一个(最佳)猜测
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于使用了 gmaps4rails_address 方法,坐标刷新是一个棘手的过程。它很灵活,易于使用,但与之相反的是,我们无法知道地址是否真的发生了变化。
这就是为什么我为编码人员提供了两种不同的机会来满足他们的需求:
将
:check_process
更改为false
:2. 如果您想完全控制进程,请将
gmaps
布尔值设置为false< /code> 每当您想要更新坐标时。它可能是表单中的隐藏字段,也可能是模型中检查必要字段的挂钩。
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:
Change
:check_process
tofalse
:2. If you want to have full control over the process, set the
gmaps
boolean tofalse
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.这是解决问题的经济方法:
添加 before_validation 函数:
def check_g4r_地址
self.gmaps = false 如果last_g4r_address != gmaps4rails_address
self.last_g4r_address = gmaps4rails_address
end
这样,仅当地址更改时才会更新地理编码
This is an economic way to solve the problem:
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.