gmaps4rails get latitude and longitude in the server

≡放荡痞女 提交于 2019-12-07 15:27:24

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

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

I would also add this:

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

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

When you you create a new post now, it will have longitude and latitude coordinates that you can use with 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

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.

Yes this can be done by geocoder.search method. I did this for getting the latitude the user's location/address .

  :lat => Geocoder.search(tweet.user.location.to_s).first.coordinates,
  :lng => Geocoder.search(tweet.user.location.to_s).first.coordinates

There is a nice railscasts here http://railscasts.com/episodes/273-geocoder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!