Rails使用Geocoder返回当前位置附近的位置

时间:2017-03-05 20:42:22

标签: ruby-on-rails rails-geocoder

我在我的rails应用程序中使用地理编码器并尝试返回当前位置附近的公园列表。下面的代码是有效的,但当然只是将公园与给定公园(当前对象)的距离返回。只是不知道如何做到这一点与当前位置。任何帮助将不胜感激。

视图中使用的代码:

<% @parks.each do |park| %>
<%park.nearbys(1.9).each do |near_park| %>
<li><%= link_to near_park.name%> (<%= near_park.distance.round(2)%> kms)</li>
<% end %>
 

控制器设置:

 class SearchController < ApplicationController

   def new
    @parks = Park.all
    @activities = Activity.all
   end

   def address
    @address = Park.find(params[:address])
    Geocode.search("@address")
   end

初​​始化器:

 Geocoder.configure(

# geocoding service:
:lookup => :google,

# IP address geocoding service:
:ip_lookup => :maxmind,

# to use an API key:
:api_key => 'API KEY',

# this is very important option for configuring geocoder with API key
:use_https => true,

# geocoding service request timeout, in seconds (default 3):
:timeout => 3,

# set default units to kilometers:
:units => :km,
 )

型号:

Class Park < ApplicationRecord
  has_many :park_activities
  has_many :activities, through: :park_activities
  has_many :events, through: :park_activities

  validates :name, :address, presence: true

  # accepts_nested_attributes_for :activities
  geocoded_by :address       # can also be an IP address
  after_validation :geocode, :if => :address_changed?

end

1 个答案:

答案 0 :(得分:1)

class ParksController
  def nearby
    @parks = Park.near([params.fetch(:lng){ 0 }, params.fetch(:lon){ 0 }], params.fetch(:radius){ 20 })
  end
end

要获取用户位置,您可以在客户端(使用ajax时)或服务器上的IP lookup中使用地理位置。

# ip based lookup example.
class ParksController
  def nearby
    @location = request.location
    if @location
      @parks = Park.near(@location)
    else
      flash.now[:error] = "Location not available"
      @parks = Park.all
    end
  end
end