Google Maps API station location two-point distance km

Calculating Distance (km) Between Stations and Locations Using Google Maps API

This article introduces how to calculate and output the distance (km) between two points like stations and locations using Google Maps API, and writes actual code.

Shou Arisaka
2 min read
Nov 25, 2025

This time, we introduce how to calculate and output the distance (km) between two points like stations and locations using Google Maps API.

Calculating Distance (km) Between Stations and Locations Using Google Maps API

When you execute the following Ruby code, it outputs the distance (km) between two points from @now_location to stations and locations in @list. Note that if you put stations and locations separated by newlines in @list, it will output the distance (km) between two points for stations and locations in @list.

Please fill in @now_location and @APIKEY yourself.

require 'net/http'
require 'json'

Encoding.default_external = 'UTF-8'

@now_location = "Sakurajosui Station"

if @list
else
@list="
Hachioji Station
Hachioji
"
@list=@list.split("\n").compact.reject(&:empty?)
end

until @list.empty?
  # puts 1
  # @location="Hachioji"
  @location = @list.pop
  @APIKEY = ""

  url="https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{@now_location}&destinations=#{@location}&mode=walking&language=ja&key=#{@APIKEY}"
  uri = URI(URI.encode(url))
  response = Net::HTTP.get(uri)
  data=JSON.parse(response)

  puts @location + ":" + km= data['rows'][0]['elements'][0]['distance']['text'] ;
  # puts @location + ":" + km= data['rows'][0]['elements'][0]['duration']['text'] ; # => Not walking time but train time? So can't use.

end

Output example (distance from Sakurajosui Station)

Kanda Station:14.1 km
Fuchu Station:15.1 km
Hachioji Station:28.8 km
Iidabashi Station:11.8 km
Nakano Station:5.7 km
Shin-Okubo Station:8.2 km
Omori Station:13.7 km
Yotsuya Station:10.0 km

Summary

In this article, we introduced how to calculate and output the distance (km) between two points like stations and locations using Google Maps API.

This program can be utilized in situations such as:

  • When you want to know the distance from a certain station or location
  • When you want to output the distance (km) between two points of stations or locations
  • Also, by outputting the distance (km) between two points of stations or locations, you can find out nearby stations or locations.

Thatโ€™s all. Thank you for reading to the end.

Share this article

Shou Arisaka Nov 25, 2025

๐Ÿ”— Copy Links