0

I am struggling to format the way that geocoder is returning the distance from one location to another.

Here is the code:

Jbuilder file:

json.array! results do |result|
  json.distance result.distance_from(@geocoded_location, units: :miles)
end

Methods:

def geocoded_location
  return unless postcode
  @geocoded_location ||= geocoder.geocode(postcode, bias: 'uk')
end

def geocoder
  Geokit::Geocoders::GoogleGeocoder
end

def postcode
  @postcode ||= params[:searchterm]
end

Now I think this all works but the result I get back is 3562.6325498137753 for the first location in the results array.

Is there a way to format the response as that is definitely not returning in miles as the two locations are less than 2 miles apart. Thought it might have been feet or meters but they are all roughly the same distance wherever you put the search from. So I think it is an issue with the geocoded location.

We are using gem 'geokit'

Any ideas or help would be greatly appreciated. If you need any further code let me know.

Georgeheap
  • 85
  • 11

1 Answers1

1

In Geocoder::Calculations module, you can calculate distance using,

distance_between(lat1, lon1, lat2, lon2, options = {}) =  ⇒ Object

Pass latitude and longitude as params,

Geocoder::Calculations.distance_between([47.858205,2.294359],
[40.748433,-73.985655]) => 3619.77359999382 # in configured units (default miles)

To get the latitude and longitude use,

Geocoder.coordinates("25 Main St, Cooperstown, NY") => [42.700149, -74.922767]

To get in result in km format, pass km as units

Geocoder::Calculations.distance_between([47.858205,2.294359],
[40.748433,-73.985655], :units => :km) => 5825.4609245084539

Ref: http://www.rubydoc.info/gems/rails-geocoder/0.9.11/Geocoder/Calculations#distance_between-instance_method

Karthik P R
  • 134
  • 5