user1010101
user1010101

Reputation: 1658

Calculating distance between two points in rails

So after spending a day, I finally got ruby geocoding installed and used it successfully in my rails.

I have a table called stop it contains fields : id, name, address, longitude, latitude.

The stop table has pre populated . I added some addresses of bus stops in the table and geocoding automatically added their respective longitude and latitude.

Now i have a small form

<%= form_tag("/welcome/index", method: "post") do %>
  <h5>Current Location</h5>
  <%= label_tag :address %><br> 
  <%= text_field_tag :address %>
 <p>
    <%= submit_tag("Submit") %>
  </p>


<% end %>

In this I capture the address entered by user in string format.

Then in my controller i convert it to longitude latitude as such

curAddress = params[:address]
@curlonglat = Geocoder.coordinates(curAddress)

So finally now i want to do a query in the Stop table and find the closest bus stop for the provided address. I was wondering what is the best way to do this? All answers are welcome.

Upvotes: 0

Views: 2722

Answers (1)

makhan
makhan

Reputation: 4009

Try geokit-rails https://github.com/geokit/geokit-rails

Add acts_as_mappable to Stop model and just use Stop.closest(origin: [lat, lng])

class Stop < ActiveRecord::Base
    acts_as_mappable defaults_units: :kms, lat_column_name: :latitude, lng_column_name: :longitude
    ...

Upvotes: 2

Related Questions