如何使用 Geocoder 计算两点之间的距离(以公里为单位)

How to calculate distance in km between two points using Geocoder

我正在尝试找出一种方法来使用 Geocoder 显示地图上两点之间的计算距离。我的 table 中有 start_address 和 destination_address,在我看来,我的模型如下所示:

class Ride < ActiveRecord::Base
    geocoded_by :start_address
    geocoded_by :destination_address
    reverse_geocoded_by :latitude, :longitude
    after_validation :geocode

end

如何计算两点之间的距离并显示在视图中。不需要经纬度。

编辑: 默认单位为 'miles'。要更改默认单位,请在您的 ActiveRecord 模型中设置它:

Venue.near([40.71, -100.23], 20, :units => :km)

或更改为:

# config/initializers/geocoder.rb
# set default units to kilometers:
:units => :km,

编辑: 我已经设法解决了这个问题:

ride = Ride.new(params)
start_address_coordinates = Geocoder.coordinates(params[:start_address])
destination_coordinates = Geocoder.coordinates(params[:destination])
ride.distance = Geocoder::Calculations.distance_between(start_address_coordinates, destination_coordinates)

Geocoder::Calculations模块中,有一个方法叫做distance_between(lat1, lon1, lat2, lon2, options = {})

你传递两点的经度和纬度,它会返回这两点之间的距离。

有关更多信息,请查看此 link

引自Gem's docs:

查找某个位置的坐标(如搜索 Google 地图)

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

所以你可以用上面的这个方法得到用户输入的特定位置的坐标,然后你可以用下面的方法计算两点之间的距离差。

埃菲尔铁塔和帝国大厦之间的距离

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