指定された住所の緯度・経度を取得し、その場所をGoogleMapに表示させる機能を作っています。
■やったこと
①rails new google_map -d postgresql
でアプリを作成
②rails g scaffold map address:string latitude:float longitude:float
③Gemfile
gem 'geocoder'
④rails db:create
⑤rails db:migrate
⑥_form.html.erb
<%= form_for(map) do |f| %> <% if map.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(map.errors.count, "error") %> prohibited this map from being saved:</h2> <ul> <% map.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :address %> <%= f.text_field :address %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
⑦show.html.erb
<script type="text/javascript"> function initMap() { var test ={lat: <%= @latitude %>, lng: <%= @longitude %>}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: test }); var transitLayer = new google.maps.TransitLayer(); transitLayer.setMap(map); var contentString = '住所:<%= @address %>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); var marker = new google.maps.Marker({ position:test, map: map, title: contentString }); marker.addListener('click', function() { infowindow.open(map, marker); }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=[googleで取得したAPIキー]&callback=initMap"> </script> <p id="notice"><%= notice %></p> <p> <strong>Address:</strong> <%= @map.address %> </p> <p> <strong>Latitude:</strong> <%= @map.latitude %> </p> <p> <strong>Longitude:</strong> <%= @map.longitude %> </p> <div id="map"></div> <%= link_to 'Edit', edit_map_path(@map) %> | <%= link_to 'Back', maps_path %>
⑧maps.scss
#map { width: 100%; height: 400px; background-color: grey; }
以上の要領で実施しましたが、マップを表示する箇所がグレー(CSSを指定した部分)になるのみで
地図が表示されません。
緯度・経度は取得できる時とそうでない時があります。
■確認したこと
・APIキーは取得できており、記載に誤りはない
・マップはCSSを指定しないと表示されないと聞いたことがあるので、
asset配下の読みこませるファイルを確認
application.js
(省略) //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree .
application.css
(省略) *= require_tree . *= require_self */
今回、下記サイトを参考にしております。
https://qiita.com/enzen/items/9a919a75ebf0a34e7b91
何が原因で表示がされないのか、
どなたかご教示いただけないでしょうか。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。