Building a small rails app that is able to search by postcode(zipcode) and radius, so it responds with contractors that are within that radius/postcode
create_table "locations", force: :cascade do |t|
Added the geocoder gem and updated the model
class Location < ApplicationRecord
after_validation :geocode, :if => :address_changed?
when i add new locations it automatically gives me the latitude and longtitude of the location
in my index view i have added the search form
<p class="lead">Use this postcode search to quickly find subcontractors in your area</p> <p><%= form_tag locations_path, :method => :get do %> <%= text_field_tag :search, params[:search], placeholder: "e.g M20 2WZ" %> <%= submit_tag "Search Near", :name => nil %> </p> <% end %>
** updated routes**
resources :locations, except: [:update, :edit, :destroy]
and in my locations controller class LocationsController < ApplicationController
@locations = Location.all
@locations = Location.near(params[:search], 10, :order => :distance)
@locations = Location.all.order("created_at DESC")
when i run the app i search for m20 2wz and in my browser i get
but does not return any results ???
Also should my location.rb model be
geocoded_by :postcode or geocoded_by :address
or is it better to do
[address, city, postcode].compact.join(‘, ‘)
For all your locations, I'd geocode them by full address. If you geocode by just the postcode then you're going to get the coordinates of that zip code, not necessarily the coordinates of the building that location represents.
After you've verified that the coordinates are correct for your locations, you then can load up the rails console and try to manually get the results... so something like
Location.near("M20 2WZ", 50) should give you some results at this point.
Location.near("M20 2WZ", 15) now shows
id: 9, company_name: "Winton Flooring Ltd", address: "46 Bury Old Rd, Whitefield", city: "manchester", postcode: "M45 6TL", latitude: 53.53980319999999, longitude: -2.2820915, created_at: "2017-07-11 10:32:46", updated_at: "2017-07-11 10:32:46">]>
Join 30,242+ developers who get early access to new screencasts, articles, guides, updates, and more.