RailsでGoogleMap APIを使う

jQueryの準備

$ yarn add jquery

(app/assets/javascript/application.js)

//= require jquery/dist/jquery.js
//= require_tree .

ENVファイルの設定、APIキーの設定

(Gemfile)

gem 'dotenv-rails'
bundle
$ touch .env

(.gitignore)

(追加)
.env

(.env)

API_KEY=(取得したAPIキー)

mapの描画

(app/views/maps/map.html.erb)

<style>
  #map {
    height: 100%;
  }
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>

<div id="map"></div>

<script>
var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 35.6581, lng: 139.7017},
    zoom: 15
  });
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<%=ENV["API_KEY"]%>&callback&callback=initMap" async defer></script>