内容
google mapを詳細画面に実装
前提
- google mapの表示機能実装済
- google mapのlatitudeとlongitudeをDBへ保存する機能実装済
- gem 'gon'を導入済
- 追記部分以外は省略
手順
hoges_controller.rb
def show
@hoge = Hoge.find(params[:id])
gon.latitude = @hoge.latitude
gon.longitude = @hoge.longitude
end
views/hoges/show.html.erb
<div class="imgmaparea"></div>
<div id="map"></div>
<% if @hoge.image.attached? %>
<%= image_tag @hoge.image, size: "150x150" %>
<% end %>
<script>
let map
let marker
let dbLat
let dbLng
function initMap(){
dbLat = gon.latitude;
dbLng = gon.longitude;
geocoder = new google.maps.Geocoder()
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: dbLat, lng: dbLng},
zoom: 12,
});
marker = new google.maps.Marker({
position: {lat: dbLat, lng: dbLng},
map: map,
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_API_KEY'] %>&callback=initMap"></script>
app/stylesheets/application.css
#map {
width: 300px;
height: 150px;
}
.imgmaparea {
display: flex;
justify-content: space-evenly;
align-items: center;
}
※ styleは自由に設定してOK
※ markerの「draggable: true」はこの画面では消している(マーカー位置を固定したいので)
コメント
gem 'gon'を導入していない場合のcontroller ⇔ js 間の変数の受け渡し方法についても学習する必要がある。