↓↓クリックして頂けると励みになります。
Rails 6を使用してGoogleの自動補完(Autocomplete)を実装するには、以下のステップに従うことができます。
Googleの自動補完は、通常、Google Places APIを使用して実装されます。
まずはGoogle Cloud PlatformにGoogleアカウントでログインしてAPIキーを取得してください。
手順は以下の通りにお願いします。
mrradiology.hatenablog.jp
GemFileに以下のgemを追加します。
gem 'geocoder', '~> 1.8', '>= 1.8.2'
ターミナルでbundle installを実行してGemをインストールします。
コマンド
bundle
モデルに以下の記述を追加します。
【app/models/report.rb】
geocoded_by :address after_validation :geocode, if: :address_changed?
「config\initializers」フォルダに「geocoder.rb」ファイルを新規作成します。
新規作成 「config/initializers/geocoder.rb」
Geocoder.configure( api_key: 'ご自分のAPIキーを入れて下さい', use_https: true, timeout: 5 )
ビューを作成します。
<script src="https://maps.googleapis.com/maps/api/js?key=ご自分のAPIキーを入力してください&libraries=places&callback=initAutocomplete" async defer> </script> <div class="container mt-4"> <div class="row"> <div class="col"> <div class="card"> <div class="card-body""> <%= f.label :現場の住所 %> <%= f.text_field :address, placeholder: "住所を入力", class: "form-control", required: true, id: "autocomplete", style: "width: 100%;" %> </div> </div> </div> </div> </div> <script> let autocomplete; function initAutocomplete() { autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete'), { types: ["establishment"], componentRestrictions: { country: ['JP'] }, fields: ["place_id", "geometry", "name"], }); } </script>
これで住所の予測変換ができるようになりました。
ジオコーディングの結果を保存するカラムをモデルに追加します。
rails generate migration AddCoordinatesToLocations latitude:float longitude:float
マイグレーションを適用します。
コマンド
rails db:migrate
住所が保存されると自動的に経度と緯度が取得され、データベースに保存されます。
経度と緯度は latitude および longitude カラムに格納されます。
↓↓クリックして頂けると励みになります。