0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習63日目

Posted at

内容

google mapで複数のマーカーを表示させ、対応するリンクをつける。

前提

  • gem 'gon' 導入済
  • google map api 導入済
  • hogesテーブルにname, latitude, longitudeのカラムがある
  • 該当部分の記述は省略

手順

コントローラでgonを記述する。
app/controllers/hoges_controller.rb

def index
  @hoges = Hoge.all
  gon.hoges = @hoges
end

javascriptでforの処理を記述する。
app/assets/javascripts/hoge_map.js

var makers = []
var infoWindows = []
var locationDatas = []

locationDatas = []
for (var i = 0; i < gon.hoges.length; i++) {
  locationDatas.push(gon.hoges[i])
}
map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: Number(locationDatas[0]['latitude']), 
      lng: Number(locationDatas[0]['longitude'])
    },
    zoom: 12,
})
   for (var j = 0; j < locationDatas.length; j++) {
     markers[i] = new google.maps.Marker({
       position: {
         lat: Number(locationDatas[j]['latitude'],
         lng: Number(locationDatas[j]['longitude']
       },
       map: map
     })
     infoWindows[i] = new google.maps.InfoWindow({
       content: '<a href="/hoge/' + {locationDatas[i]['id']}  + '">' + locationDatas[i]['name'] + '</a>'
      })
      markerClick(j)
  function markerClick(j) {
    markers[j].addListener('click', function() {
      infoWindows[j].open(map, marker[j])
    })
  }

コメント

おおよそ予想通りのロジックで実装できた。
gonで取得するハッシュのバリューは文字列に自動で変換されてしまうと考えられる。
(Number()を使わないとlatitudeとlongitudeが数値として認識されなかった)

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?