This Ruby program uses the Google Maps Distance Matrix API to retrieve and display distance information between two locations. Below is a step-by-step explanation of the program.
Encoding.default_external = 'UTF-8'
require 'json'
require 'open-uri'
# Use Google Maps Distance Matrix API to retrieve distance information between two locations.
# Set the departure point and arrival point in the following two variables respectively.
@here = '東京'
@dist = '大阪'
# Build the API request URL. The URL includes the departure point (@here), arrival point (@dist), mode of travel (here walking), language (ja=Japanese), and API key.
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{@here}&destinations=#{@dist}&mode=walking&language=ja&key=YOUR_API"
# Encode the URL, send a request to the API using open-uri, and load the result as JSON.
puts @obj = JSON.load(open(URI.encode(url))
# Retrieve necessary information from the JSON response.
# Get destination address
@destination_addresses = @obj['destination_addresses'][0]
# Get origin address
@origin_addresses = @obj['origin_addresses'][0]
# Get distance information (text format)
@km = @obj['rows'][0]['elements'][0]['distance']['text']
# Display results
puts "Current location"
puts @here, @origin_addresses
puts "Destination"
puts @dist, @destination_addresses
puts "Distance"
puts @km
This program specifies a departure point (@here) and arrival point (@dist), and uses the Google Maps Distance Matrix API to retrieve distance information between these locations. The response from the API is in JSON format, which is parsed to extract the necessary information and finally display the departure point, arrival point, and distance. To use the Google Maps Distance Matrix API in detail, you need to provide an API key (the ‘YOUR_API’ part) to make requests.