9
16

More than 3 years have passed since last update.

【Rails】Google Mapに複数マーカーを表示し、クリックしたら吹き出しを出す方法

Last updated at Posted at 2020-06-04

目標

ezgif.com-video-to-gif.gif

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
ログイン機能実装
Google Map表示
Gocoding APIで緯度経度を算出

実装

1.コントローラーを編集

users_controller.rb
def index
  @users = User.all
  gon.users = User.all
end

2.ビューを編集

users/index.html.slim
#map style='height: 500px; width: 500px;'

- google_api = "https://maps.googleapis.com/maps/api/js?key=#{ ENV['GOOGLE_MAP_API'] }&callback=initMap".html_safe
script{ async src=google_api }

javascript:

  let map;
  let marker = []; // マーカーを複数表示させたいので、配列化
  let infoWindow = []; // 吹き出しを複数表示させたいので、配列化
  let markerData = gon.users; // コントローラーで定義したインスタンス変数を変数に代入

  function initMap() {
    geocoder = new google.maps.Geocoder()

    map = new google.maps.Map(document.getElementById('map'), {
      center: { lat: 35.6585, lng: 139.7486 }, // 東京タワーを中心に表示させている
      zoom: 12,
    });

    // 繰り返し処理でマーカーと吹き出しを複数表示させる
    for (var i = 0; i < markerData.length; i++) {
      let id = markerData[i]['id']

      // 各地点の緯度経度を算出
      markerLatLng = new google.maps.LatLng({
        lat: markerData[i]['latitude'],
        lng: markerData[i]['longitude']
      });

      // 各地点のマーカーを作成
      marker[i] = new google.maps.Marker({
        position: markerLatLng,
        map: map
      });

      // 各地点の吹き出しを作成
      infoWindow[i] = new google.maps.InfoWindow({
        // 吹き出しの内容
        content: markerData[i]['address']
      });

      // マーカーにクリックイベントを追加
      markerEvent(i);
    }
  }

  // マーカーをクリックしたら吹き出しを表示
  function markerEvent(i) {
    marker[i].addListener('click', function () {
      infoWindow[i].open(map, marker[i]);
    });
  }

吹き出しの内容ををリンクにしたい場合は下記の様に記述する。

// 各ユーザーのIDを変数化
let id = markerData[i]['id']

infoWindow[i] = new google.maps.InfoWindow({
  // <a>タグでリンクを作成
  content: `<a href='/users/${ id }'>${ markerData[i]['address'] }</a>`
});

注意

turbolinksを無効化しないと地図が切り替わらないので、必ず無効化しておきましょう。

turbolinksを無効化する方法

9
16
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
9
16