Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajdeep26/5527863 to your computer and use it in GitHub Desktop.
Save rajdeep26/5527863 to your computer and use it in GitHub Desktop.
Ruby code to get distance between two places using Google Maps Distance API where places are specified by their latitude and longitude..
require "net/http"
require "json"
def find_distance(lat1,long1,lat2,long2)
uri = URI("http://maps.googleapis.com/maps/api/distancematrix/json?origins=#{lat1},#{long1}&destinations=#{lat2},#{long2}&mode=driving&sensor=false")
response = Net::HTTP.get_response(uri)
distancematrix = JSON.parse(response.body)
#puts distancematrix
puts "Origin Address: #{distancematrix["origin_addresses"]}"
puts "Destination Address: #{distancematrix["destination_addresses"]}"
rows=distancematrix["rows"]
rows.each do |row|
elements = row["elements"]
puts elements.class
elements.each do |element|
puts "Distance(km): #{element["distance"]["text"]}"
puts "Distance(value): #{element["distance"]["value"]}"
puts "Duration(text): #{element["duration"]["text"]}"
puts "Duration(value): #{element["duration"]["value"]}"
end
end
end
find_distance(27.17,78.04,27.19,78.03)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment