gmaps4rails 在服务器中获取纬度和经度 [英] gmaps4rails get latitude and longitude in the server

查看:28
本文介绍了gmaps4rails 在服务器中获取纬度和经度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 'gmaps4rails' 的信息,但我有一个关于 gem 的问题.是否可以仅通过地址获取位置(lat,lng)?

I'm reading about 'gmaps4rails', but I have a question about the gem. Is possible obtain the location (lat, lng) only with the address?

推荐答案

是的,但我会首先使用 Geocoder gem.

Yes it is, but I would first use the Geocoder gem.

gem 'geocoder'

您需要创建一个迁移以将纬度和经度浮点数添加到您的表中

You need to create a migration to add latitude and longitude floats to your table

rails g migration AddLatitudeAndLongitueToModel latitude:float longitude:float

显然,将 Model 替换为您的表名.然后运行 ​​rake db:migrate

Obviously, replace Model with your table name. then run rake db:migrate

然后在您的模型中,确保对地址的属性进行地理编码

Then in your model, make sure the attribute for an address is being geocoded

geocoded_by :location # replace location with the attribute of the address

我还要加上这个:

after_validation :geocode, if: ->(model_name){ model_name.location.present? and model_name.location_changed? }

避免不必要的 API 请求.再次将 model_name 更改为您的模型,并将 location 更改为具有地址的属性.

to avoid unnecessary API requests. Once again, change model_name with your model and location with the attribute that has the address.

当你现在创建一个新帖子时,它会有经纬度坐标,你可以使用 Gmap4rails

When you you create a new post now, it will have longitude and latitude coordinates that you can use with Gmap4rails

所以你现在可以像这样Gmap4rails:

So you can now you Gmap4rails like this:

hash = Gmaps4rails.build_markers(@post) do |post, marker|
  marker.lat post.latitude
  marker.lng post.longitude
end

这是 Geocoder gem 的 GitHub 文档.几乎拥有将其添加到应用程序所需的一切.

Here is the GitHub docs for the Geocoder gem. Has pretty much everything you need to know to add this to your app.

希望这能让您朝着正确的方向开始.

Hope this can get you started in the right direction.

这篇关于gmaps4rails 在服务器中获取纬度和经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆