GoogleMapの導入とAPIによるジオコーディング

rails6にて表記の件を導入した際に備忘録。

なお、APIの取得等は他サイトでも紹介されている為、そちらを参考に。

https://www.zenrin-datacom.net/business/media/g001/

こちらではコードやうまくいかなかったことを記載する。

 

・取得Google  Map API

Maps JavaSript API

Geocoding API

 

Google Maps APIキーの取得後、かつGeocoding APIを取得後

 

<div id="map" class="map-window"></div>
#大きさを指定しないと表示されない
 
<script type="text/javascript">
var map;
var marker;
var geocoder;
function initMap() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': '<%= @post.prefecture+@post.city+@post.address+@post.building_name %>'
#こちらはDBから取得した住所情報とする
 
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map = new google.maps.Map(document.getElementById('map'), {
center: results[0].geometry.location,
zoom: 17
});
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
#ピンの場所についての情報
});

} else {
alert(status);
#エラーコード
}
});
}
</script>
<%=ENV['MAP_API_KEY']%>&callback=initMap" async></script>
環境変数APIを表示

 

class、styleによる大きさの指定をしなければ表示されない。

また、APIコードは悪用防止の為、環境変数にて設定する。