2017-03-05 7 views
0

Ich verwende Geocoder mit meiner App rails und versuche, eine Liste der Parks in der Nähe meines aktuellen Standortes zurückgeben. Der Code unten funktioniert, aber natürlich nur die Parks ihre Entfernung von einem bestimmten Park (aktuelles Objekt). Ich bin mir nicht sicher, wie man das gegen den aktuellen Standort macht. Jede Hilfe würde sehr geschätzt werden.Schienen Orte in der Nähe des aktuellen Standorts mit Geocoder

-Code in der Ansicht verwendet:

<% @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 %> 

Controller Setup:

class SearchController < ApplicationController 

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

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

Ende

Initializer:

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, 
) 

Modell:

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 

Antwort

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

Um die Benutzer Position erhalten Sie entweder Geolocation im Client (bei Verwendung von Ajax) oder ein IP lookup auf dem Server verwenden können.

# 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 
+0

Vielen Dank für die Antwort Max. Ich bin ein Anfänger also bitte bare mit mir. Ich verstehe nicht, wie man die IP-Suche auf dem Server durchführt. Der Initialisierer ist so konfiguriert, dass er verwendet: ip_lookup =>: maxmind, aber ich weiß nicht, wie ich ihn verwenden soll. – frankburke333

+0

Sie können 'request.location' verwenden, das nil oder ein' Geocoder :: Result'-Objekt zurückgibt. – max

Verwandte Themen