GoogleMap APIを使い、地図上にマーカーを落とし、その場所の緯度経度を取得する方法を学んだので備忘録のため、書きます。
※APIキーは事前に取得している前提
緯度・経度の入れ物を作る
new・editのページを想定して作っています。
_form.html.erb
<%= form_with(model: place, local: true) do |form| %>
<% if place.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(place.errors.count, "error") %> prohibited this place from being saved:</h2>
<ul>
<% place.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :latitude %>
<%= form.text_field :latitude, {id: "target_latitude"} %>
</div>
<div class="field">
<%= form.label :longtitude %>
<%= form.text_field :longtitude, {id: "target_longtitude"} %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
<style>
/* マップを表示する div 要素の高さを必ず明示的に指定します。 */
#map {
height: 400px;
width: 600px;
}
</style>
<div id="map"></div><!-- 地図を表示する div 要素(id="map")-->
javascript部分
var map;
function initMap() {
var myLatlng = new google.maps.LatLng(35.681167, 139.767052);
//インスタンスを作成
map = new google.maps.Map(document.getElementById('map'), {
//地図のオプション
//初期のズームレベル
zoom: 12,
//地図の中心点
center: myLatlng
});
//マーカーの初期プロパティを指定
marker = new google.maps.Marker({
position: myLatlng,
//ドラッグを許可
draggable: true,
map: map,
});
//マーカーのドロップ(ドラッグ終了)時のイベント
google.maps.event.addListener(marker, 'dragend', function(e) {
//イベントの引数eの、プロパティ.latLngがmarkerの緯度経度。
document.getElementById( "target_latitude" ).value = e.latLng.lat(),
document.getElementById( "target_longtitude" ).value = e.latLng.lng()
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<script src="https://maps.googleapis.com/maps/api/js?key=【APIキー】&callback=initMap" async defer></script>
参考文献:https://mapsflow.blogspot.com/2018/03/maps-javascript-api_22.html