Rails

Rails App That Returns Distance When You Request with Current Location and Destination in URL

Shou Arisaka
1 min read
Oct 2, 2025

I created an app like that with Rails.

This is probably the first Rails app that feels right... Until now, I was just copy-pasting blogs and using scaffolds.

It didn't take much time because I just converted something I originally made in PHP to work with Rails. But I tried it as practice.

// routes.rb
get 'userinfo/show/:here/:dist' => 'userinfo#show',as:'userinfo_show'
// userinfo_controller.rb
  def show

    Encoding.default_external = 'UTF-8'
    require 'json'
    require 'open-uri'

    @here = params[:here]
    @dist = params[:dist]
    # @here = 'æ±äº¬'
    # @dist = '大阪'

    url="https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{@here}&destinations=#{@dist}&mode=walking&language=ja&key=YOUR_API"
    puts @obj = JSON.load(open(URI.encode(url)))

    @destination_addresses= @obj['destination_addresses'][0] ;
    @origin_addresses= @obj['origin_addresses'][0] ;
    @km= @obj['rows'][0]['elements'][0]['distance']['text'] ;

  end
// show.html.erb
<p>現在地: <%= @origin_addresses %> </p>
<p>目的地: <%= @destination_addresses %> </p>
<p>距離: <%= @km %> </p>

This uses the Google Maps API.

Please change YOUR_API to your own.

Now, when you access http://localhost:3000/userinfo/show/東京/大阪,

<br />現在地: 日本、東京都東京

目的地: 日本、大阪府大阪市

距離: 493 km

It will display something like this.

Share this article

Shou Arisaka Oct 2, 2025

🔗 Copy Links