LoginSignup
6

More than 5 years have passed since last update.

[RoR]railsにgoogle map を表示する

Last updated at Posted at 2015-12-30

概要

RubyOnRailsにgoogle map のjqueryプラグインの導入したときの手順
RubyOnRailsにはGoogle-Maps-for-Railがあるけど、オプションの設定方法などが、いまいちわからりずらかった。
そこでjqueryのプラグインのjquery.gmap3を使いました。

環境

Ruby 2.2.2
Rails 4.2.3

google mapを表示する

1.必要なjsを取得、格納

githubからjquery.gmap3をDL(Download ZIPから取得)

DLした中からjquery.gmap3.jsを取り出し、プロジェクトDir/vendor/assets/javascripts/に格納

2.プロジェクトにinclude

プロジェクトDir/app/views/layouts/application.html.erbにGoogleMapAPIをincludeする

application.html.erb
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<%= javascript_include_tag "application" %>

プロジェクトDir/app/assets/javascripts/application.jsにjquery.gmap3.jsをincludeする

application.js
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
//= require jquery.gmap3

*twitter boot strapを導入しているとjquery部分が先に記述されている

3.google mapを表示したいviewを編集

view
<div id="gmap3"></div>
<script>
  $(function() {
    $('a[href="#map-tab"]').on('shown.bs.tab', function(e) {
      $("#gmap3").gmap3({
        address: '表示したい住所',
        zoom: 16,
        navigationControl: true,
        mapTypeControl: true,
        scaleControl: true,
        markers: [{
          address: '表示したい住所(マーカー)',
        }]
      });
      $.gmap3.panTo($("#gmap3"), {address: '中心にしたい住所'});
      google.maps.event.trigger(gmap3, 'resize');
    });
  });
</script>

*緯度経度でも設定できるが、google mapで取得した緯度経度を設定すると、何故かずれてしまうので、住所で設定している

twitter bootstrap のタブ中にgoogle mapを配置すると、タブ変更時に巧く描画できない。
そこで、タブをクリックされた際に、google mapがrisizeされるようにjsを記述する。

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
6