0
0

GoogleMapsAPIを使用した開発2(現在地取得)

Posted at

1.はじめに

投稿された情報(緯度経度)からGooleMapsAPIを使用して地図を表示、地点間のルート検索機能、周辺情報の取得を実装したので知識の定着、復習のために記事を書きます。
一度に書くと長くなるので、4回にわけて投稿していきます。
今回はその2回目で現在地取得まで実装します。

2.環境

Ruby (2.6.4)
Rails (6.1.7)
Maps JavaScript API

3.前提条件

APIキー取得済み
投稿機能を実装している
GoogleMapsAPIを使用した開発1(地図の表示)まで実装している

4.実装

1.viewの修正

      <div class="map">
        <div id="map_index"></div>
+       <div><button id="current-location-button" class="btn btn-primary">現在地を取得する</button></div> # 追記
      </div>

2.現在地を取得しマーカーを追加、ボタンにクリックイベントを追加

  const currentLocationButton = document.getElementById('current-location-button'); // ①
  currentLocationButton.addEventListener('click', getCurrentLocationAndAddMarker); // ②

document.getElementById('current-location-button')でHTML内のcurrent-location-buttonというIDを持つ要素を取得しています。

②.addEventListener('click', getCurrentLocationAndAddMarker)で取得した要素に対して、クリックイベントが発生したときにgetCurrentLocationAndAddMarker関数を呼び出すようにイベントリスナーを追加しています。

  • これにより、ユーザーがボタンをクリックすると、getCurrentLocationAndAddMarker関数が実行されます。
  • getCurrentLocationAndAddMarker関数については次で説明していきます。

3.現在地を取得しマーカーを追加する関数を作成(getCurrentLocationAndAddMarker関数)

  // 変数宣言
  let currentLocationMarker; // 現在地のマーカー

  function getCurrentLocationAndAddMarker() {
    if (navigator.geolocation) { // ①
      navigator.geolocation.getCurrentPosition(function (position) { // ②
        const currentLatLng = { // ③
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        if (currentLocationMarker) { // ④
          currentLocationMarker.setMap(null);
        }
        currentLocationMarker = new google.maps.Marker({ // ⑤
          position: currentLatLng,
          map: map,
          title: "現在地"
        });

        currentLocationMarker.addListener('click', function () { // ⑥
          infoWindow.setContent(
            `<strong> 現在地 </strong>`
          );
          infoWindow.open(map, currentLocationMarker);
        });

        map.setCenter(currentLatLng); // ⑦

      });
    } else { // ⑧
      alert("このブラウザでは位置情報が利用できません");
    }
  }

if (navigator.geolocation) { でブラウザが位置情報をサポートしているかを確認しています。

  • サポートされている場合は、位置情報の取得を試みます。

navigator.geolocation.getCurrentPosition(function (position) {でユーザーの現在の位置情報を非同期で取得します。

  • 成功時には、コールバック関数が実行され、取得された位置情報が position パラメータとして渡されます。

③では、positionオブジェクトから緯度と経度を取り出し、currentLatLng オブジェクトに格納します。

④は、既に地図上に表示されているマーカーがあれば削除するコードです。

⑤取得した位置に新しいマーカーを作成し、地図上に表示します。

⑥マーカーがクリックされた時の動作を追加します。マーカーをクリックすると、現在地と表示されたInfoWindowが開きます。

  • openメソッドの最初の引数mapは、InfoWindowを表示する地図オブジェクトです。
  • 2番目の引数currentLocationMarkerは、InfoWindowをどのマーカーに関連付けて表示するかを指定します。
  • 今回の場合、currentLocationMarkerは現在地を示すマーカーです。

map.setCenter(currentLatLng);で地図の中心を現在地に設定します。

⑧は、ブラウザが位置情報をサポートしていない場合には、アラートで通知するコードです。

5.おわりに

ここまでで、現在地取得機能を実装できました。
間違いがあればご連絡いただけると助かります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0