Open2
ジオコードapi、マップapi

雑にコメント突っ込んで後で解説できるようにしておく
// コントローラー側で取り出した紹介状テーブルの情報をビューに渡す
// 複数渡されるため一個づつ取り出すためforeach
<div class="address-choice" style="display: none;">
@foreach ($spot as $item)
<div class="item-unique">
<p class="item-in-address">
スポット名:{{$item->spotname}},住所:{{$item->address}}
</p>
<p>
{{$item->id}}
</p>
</div>
@endforeach
</div>
<script>
function initMap() {
// グーグルマップのマップapiをインスタンス化
// マップの表示領域を指定する
let map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {
lat: 36.653141021728516,
lng: 150.644
}
});
// googleマップのジオコードapiをインスタンス化
let geocoder = new google.maps.Geocoder();
geocodeAddress(geocoder, map);
}
function geocodeAddress(geocoder, resultsMap) {
// ここに紹介状テーブルのアドレス列の数字を一個づつ入れて行って処理を実行したい
// 後で使う変数を定義
// コントローラー側で取り出した紹介状のアドレスとスポット名を取得
let addresspin = document.querySelectorAll('.address-choice .item-in-address')
let spotname = document.querySelectorAll('.address-choice .item-in-spotname')
let origin = location.origin;
// 吹き出しを閉じるのに使う配列を作成
let infoWindows = [];
// 動的にピンを立て、ピンに紐づく吹き出しの内容も動的に変化させる
// コントローラー側で取り出した紹介状のアドレスを使用してジオコーディング(住所を緯度、経度に変換)
addresspin.forEach(function(element) {
// コントローラー側で取り出してきた紹介状のIDをトリム
let getMapid = (element.nextElementSibling.textContent).trim();
// 吹き出しに紹介状へのリンクを付与するのに使用
let routesmap = '/syoukaijou/' + getMapid + '/';
// 吹き出しに表示したい内容(動的)
let spotinfo = '<div class="sample"><a href=" ' + origin + routesmap + '">' +
element.textContent.replace(',', '<br>') +
'</a></div>';
let trimname = element.textContent.substr((element.textContent).indexOf(',') + 4);
// 住所を緯度経度に変換し、変換した内容を中心にした地図を表示し、ピンと吹き出しをつける。
geocoder.geocode({
// アドレスの引数に住所情報を入力
'address': trimname
}, function(results, status) {
// results:アドレスを緯度経度に変換した結果が格納
// status:アドレスを緯度経度に変換できた場合は'ok'できなかった場合は返り値なし
if (status === 'OK') {
console.log(results);
// 結果を返すマップの中心を指定
resultsMap.setCenter(results[0].geometry.location);
// ピンを立てる処理
let marker = new google.maps.Marker({
// どのマップにピンを立てるかを指定
map: resultsMap,
// 地図のどこにピンを立てるか指定
position: results[0].geometry.location,
});
// 吹き出し
let infoWindow = new google.maps.InfoWindow({
// :後の変数展開がうまく行かなかったので先に変数を定義したものを使用
content: spotinfo
});
// infoWindow を配列に追加
infoWindows.push(infoWindow);
// ピンにイベントを設定
marker.addListener('click', function() {
// 開いている infoWindow を閉じる、押したピンに関わる吹き出しを閉じるためにforeach
infoWindows.forEach(function(infoWin) {
infoWin.close();
});
// クリックしたマーカーに関連する infoWindow を開く
infoWindow.open(map, this);
});
}
});
})
};
</script>

基本的にこの順番
- マップを表示する領域をhtml上に作る
- apiをbodyタグの一番下に読み込む
- マップの表示領域、中心などを定義
- ピンの表示、ジオコードapiによる住所と緯度経度の変換等する。
- 押したピン以外を閉じる