0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GoogleMapsAPIを使って位置情報を取得してみた

Last updated at Posted at 2025-04-23

はじめに

現在オリジナルプロダクトを作成しており、その中で現在地を取得し周辺の店舗情報を取得、表示する機能を実装しました。
Rails + erb構成となっています。

使用するAPI

実装内容

1. APIキーの設定

Google Maps APIが使用できるように環境変数へ設定しスクリプトを読み込ませる

  • key=<%= ENV["GOOGLE_MAPS_API_KEY"] %> → 環境変数からAPIキーを取得
  • libraries=places → Places APIを利用するために指定
  • callback=initMap → Google Mapの初期化関数を指定

<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV["GOOGLE_MAPS_API_KEY"] %>&libraries=places&callback=initMap" async defer></script>

2. コードの全体


  <script>
  window.initMap = function () {
    navigator.geolocation.getCurrentPosition((position) => {
      const userLocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      const map = new google.maps.Map(document.getElementById('map'), {
        center: userLocation,
        zoom: 15
      });

      const image = "https://maps.google.com/mapfiles/ms/icons/blue-dot.png";

      new google.maps.Marker({
        position: userLocation,
        map: map,
        title: "あなたの現在地",
        icon: image
      });

      nearShowStore(map, userLocation);
    });
  };

  function nearShowStore(map, userLocation) {
    const service = new google.maps.places.PlacesService(map);

    service.nearbySearch({
      location: userLocation,
      radius: 5000,
      keyword: "古着屋 リサイクルショップ"
    }, (results, status) => {
      results.forEach((place) => {
        const marker = new google.maps.Marker({
          position: place.geometry.location,
          map: map,
          title: place.name,
        });

        const contents = `
          <div>
            <strong>${place.name}</strong><br>
            <strong>住所:</strong>${place.vicinity}
          </div>`;

        const infoWindow = new google.maps.InfoWindow({
          content: contents
        });

        marker.addListener('mouseover', () => {
          infoWindow.open(map, marker);
        });

        marker.addListener('mouseout', () => {
          infoWindow.close();
        });
      });
    });
  }
</script>

3. 各コードの解説

window.initMap = function () {}
  • Google Maps APIの読み込み完了時に自動で実行される初期化関数

  • callback=initMap に対応するため、グローバルスコープに定義する必要がある

navigator.geolocation.getCurrentPosition()
  • ブラウザの現在地取得API(Geolocation API)
  • 成功時に position.coords.latitude / longitude を取得
new google.maps.Map()
  • 取得した位置情報を中心に地図を表示
  • zoom: 15 はマップの拡大率
new google.maps.Marker()
  • 現在地に青いマーカー(カスタムアイコン)を設置
PlacesService().nearbySearch()
  • userLocation を中心に、半径5000m以内の「古着屋」「リサイクルショップ」を検索
  • 検索結果ごとにマーカーを設置し、クリックすると InfoWindow を表示

まとめ

  • Google Maps API を使えば、現在地の地図表示と周辺店舗の検索表示が簡単にできる
  • Geolocation API で現在地を取得し、Places API でキーワード検索が可能
  • マーカーとクリック時の情報表示(InfoWindow)ができる
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?