学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Ruby on Rails | Googleマップの利用

↓↓クリックして頂けると励みになります。



Googleマップを表示させるには、まずGoogle Cloud PlatformでAPIキーを取得する必要があります。


Google Cloud PlatformにGoogleアカウントでログインしてAPIキーを取得してください。
手順は以下の通りにお願いします。
mrradiology.hatenablog.jp


GeocoderやAutocompleteと組み合わせると経度緯度の取得が楽になります。
mrradiology.hatenablog.jp


コマンド
rails g migration AddFieldsToRoom latitude:float longitude:float


コマンド マイグレーション
rails db:migrate


GoogleマップAPIの埋め込み
取得したキーを「key=」から「&callback」の間に埋め込んで下さい。

<script async defer src="https://maps.googleapis.com/maps/api/js?key=ここにご自分のAPIキーを埋め込みます&callback=initMap" type="text/javascript"></script>



このscriptタグをサイトに埋め込みます。


1.記述追加 app\views\reports\show.html.erb

<script async defer src="https://maps.googleapis.com/maps/api/js?key=ここにご自分のAPIキーを入力してください&callback=initMap" type="text/javascript"></script>
            <!-- GOOGLE マップ -->
            <div class="card mt-4 mb-4">
                <div id="map" style="width: 100%; height: 400px"></div>
                <script src="https://maps.googleapis.com/maps/api/js"></script>
                <script>
                    function initialize() {
                        var location = {lat: <%= @report.latitude %>, lng: <%= @report.longitude %>};
                        var map = new google.maps.Map(document.getElementById('map'), {
                        center: location,
                        zoom: 14
                        });
                        var marker = new google.maps.Marker({
                        position: location,
                        map: map
                        });
                        var infoWindow = new google.maps.InfoWindow({
                        content: '<div id="content"><%= image_tag report_cover(@report), class: "imgt2" %></div>'
                        });
                        infoWindow.open(map, marker);
                    }
                    google.maps.event.addDomListener(window, 'load', initialize);
                </script>
            </div>



画像表示させるためにヘルパーを利用しています。
「app/helpers/application_helper.rb」

module ApplicationHelper
    
    def report_cover(report)
        if report.photos.attached?
            url_for(report.photos[0])
        else
            ActionController::Base.helpers.asset_path('no_image_logo.png')
        end
    end        

end



これでGoogleマップ表示ができるようになりました。

Googleマップ表示
Googleマップ表示




↓↓クリックして頂けると励みになります。