LoginSignup
142
153

More than 5 years have passed since last update.

Rails4でGoogleMapを表示させる

Last updated at Posted at 2013-11-14

RailsでGoogleMapを表示させたい!

と思って調べてみたら、早速出てきました。
その名もGoogle Maps for Rails

早速使ってみる

Githubに載っているチュートリアルに従ってコードを書いて行きます。
YouTubeにも動画が上がっています

とりあえずプロジェクトを用意します。

rails new gmap 
cd gmap

用意するGemを記述

Gemfile
gem "gmaps4rails"
gem "geocoder"
bundle install

緯度経度のデータを格納するModelを用意します。

rails g scaffold user title:string description:string address:string latitude:float longitude:float
rake db:migrate

Userができたら以下のコードを記述します。

user.rb
class User < ActiveRecord::Base
  geocoded_by :address
  after_validation :geocode
end

JSのURLを指定します

views/layouts/application.html.erb
<script src="//maps.google.com/maps/api/js?v=3.13&amp;sensor=false&amp;libraries=geometry" type="text/javascript"></script>
<script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js' type='text/javascript'></script>

underscore.jsはこちらよりコピーしてきます。

vendor/assts/javascripts/underscore.js
(省略)
assets/javascripts/application.js
//= require underscore
//= require gmaps/google

地図ページを用意します

rails g controller map index
views/map/index.html.erb
<div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>

<script type="text/javascript">
    handler = Gmaps.build('Google');
    handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
      markers = handler.addMarkers(<%=raw @hash.to_json %>);
      handler.bounds.extendWith(markers);
      handler.fitMapToBounds();
    });
</script>

Controllerを編集します

controllers/map_controller.rb
class MapController < ApplicationController
  def index
    @users = User.all
    @hash = Gmaps4rails.build_markers(@users) do |user, marker|
      marker.lat user.latitude
      marker.lng user.longitude
      marker.infowindow user.description
      marker.json({title: user.title})
    end
  end
end

Userデータを登録

この時点で先にUserにデータを入れておきます。
Userの作成ページにて、Addressに適当な地名を入力します。
更新時にgmap4railsのほうで緯度経度を取得してLatitide/Longitudeに格納してくれます。
どの程度までかわかりませんが、日本語で登録しても問題ないようです。
こんな感じで。

title address latitude longitude
名古屋の場所 名古屋 35.1814464 136.906398
浜松の場所 浜松 34.7108344 137.7261258
静岡の場所 静岡 34.975562 138.3827956

動作確認!

さて、いよいよ起動です。
rails s してlocalhost:3000/map/indexにアクセスしてみます。
デフォルトのままだと味気ないのでTwitterBootstrapRailsを見た目を多少整えています。

My

というわけで

簡単でしたね。
ここまででYouTubeの動画の半分くらいです。後半は色々なオプションの説明となっていました。
それ以外の機能についてはWikiのほうに色々書いてあるみたいですよ。

142
153
19

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
142
153