##ロードしない限り、前に検索した場所のマーカーが消えません。
現在、railsでGoogleMapAPIを使用し、地図検索機能を実装しております。
gem "geocooder"も導入し、検索したらその位置にマーカーが表示されるまで設定できました。
ただ、続けて検索すると
その前に検索した位置のマーカーが残り続けてしまいます。
おそらく、jsファイルの記述が足りていないか、
もしくはajax非同期をしているからなのか?とわからない状況です。
ご教授いただけると幸いです。
###コード
Gemfile
1gem 'geocoder'
route.rb
resources :maps, only:[:index] get '/map_request', to: 'maps#map', as: 'map_request' #追記
index.html.erb
<div class="map-title"> <h2>地図検索</h2> <%= form_with url: map_request_path, method: :get do |f|%> <%= f.text_field :address %> <%= f.submit '地図表示' %> <% end %> </div> <div id='map'></div> <script src="https://maps.googleapis.com/maps/api/js?key=API_key&callback=initMap" async defer></script> API_keyには、発酵してあるAPIキーを入れております。質問のため、隠しております。
application.js
let mapInstance; function initMap() { mapInstance = new google.maps.Map(document.getElementById("map"), { center: { lat: 35.681236, lng: 139.767125 }, zoom: 15, }); }
map.js.erb
(function(){ // 位置情報をもつ変数を用意 let pos = new google.maps.LatLng( <%= @latlng[0] %>, //latitude <%= @latlng[1] %> //longitude ); mapInstance.setCenter(pos) let marker = new google.maps.Marker({ map: mapInstance, position: pos }); })()
###参考にしたサイト
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/04/01 01:13