##環境
Ruby 2.1.0
Rails 4.1.0
geocoder 1.3.7
gmaps4rails 2.1.2
##GoogleMapsでマーカー位置座標の取得
Railsで店舗検索サイトを作成しています。
GoogleMaps表示にはgmaps4rails
を用いています。
店舗情報は店舗が直接入力出来るようにしています。
gemgeocoder
を用いて入力してもらった住所から緯度・経度を自動で取得し、GoogleMapsにマーカーを落とすようにしましたが実際の位置とはズレている事が多いです。
位置にズレがある場合は編集ページ(shop/edit.html.erb)で補正する方法はありませんでしょうか。
GoogleMapsに表示されるマーカーを直接動かして、その位置の緯度・経度を取得しデータベースに保存できればベストだと考えています。
マーカー位置をドラッグでの移動は出来ましたが、緯度・経度の再取得とデータベースでの更新方法が分からずにいます。
なんとなく、更新時もgeocoder
が作動して住所から自動で取得された座標が反映されてしまっている気もしますが。。
shops_contrller.rb def edit @shop = Shop.find(params[:id]) @hash = Gmaps4rails.build_markers(@shop) do |shop, marker| marker.lat shop.latitude marker.lng shop.longitude marker.infowindow shop.name marker.json({ title: shop.name }) end respond_with(@shop) end
view/shops/edit.html.erb <script type="text/javascript"> handler = Gmaps.build('Google'); //データベースに保存されている座標を取得 handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){ var markers = handler.addMarkers(<%= raw @hash.to_json %>,{draggable: true}); handler.bounds.extendWith(markers); handler.fitMapToBounds(); }); //add markers to original json _.each(<%= raw @hash.to_json %>, function(json, index){ json.marker = markers[index]; }); //add dragend event to markers, triggered when you drop them _.each(<%= raw @hash.to_json %>, function(json){ google.maps.event.addListener(json.marker.getServiceObject(), "dragend", function(event) { var lat = event.latLng.lat(); var lng = event.latLng.lng(); console.log('Marker with id: ' + json.id + ' dropped hat lat: ' + lat + ' and lng: ' + lng) }); }); </script>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/07/15 08:45
2016/07/15 09:00