2
2

More than 1 year has passed since last update.

Rails iframeでサクッと作る地図機能

Last updated at Posted at 2022-10-12

地図機能を調べると結構な割合でGoogleのAPIがヒットしますが
もっと楽に作れたので、共有です🙌

地図機能 作り方

  1. iframeの準備
  2. railsのViewで代入

この手順で終わりです!!

1. iframeの準備

今回使用するiframeはこちらになります。

<iframe
    src="https://www.google.com/maps/?output=embed&t=h&z=8&q=東京駅" 
    width="600"
    height="450"
    frameborder="0"
    style="border:0"
    allowfullscreen
>
</iframe>

このiframeをカスタマイズしたり、パラメータ(URLのところに出てくるクエリ的なもの)を
いじったりして作成します!

パラメータの解説

今回使用するGoogleMapのパラメータは以下のようになっています

パラメータ 使い方
q 住所の指定(地名or緯度・経度を入れる)
ll 地図の中心位置、緯度・経度で指定
t 表示モード
m:地図, k:航空地図, h:地図+航空写真,
p:地形図, e:Google Earth
z 地図の縮尺, 0~23で倍率指定

2. railsで代入

今回は、Postテーブルにtitle: string(投稿タイトル)、site: string(地名)が
あり、そのデータをposts_controller内で@post = Post.find(params[:id])にて取得している前提になります。

posts/show.html.erb
<%= @post.title %>
<iframe
    src="https://www.google.com/maps/?output=embed&t=h&z=8&q=<%= @post.site %>" 
    width="600"
    height="450"
    frameborder="0"
    style="border:0"
    allowfullscreen
>
</iframe>

これで簡単に作れる地図機能は終わりです!
あとは、大きさなどをCSSでカスタマイズするだけで、JSを使ったMapと似たような
ことができるので、トライしてみてください🙌

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2