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?

ポートフォリオ作成時メモ part10 ~Google Maps API 大幅改善~

Last updated at Posted at 2024-12-17

はじめに

こんにちは、未経験からエンジニア転職を目指しているものです。
オンラインスクールで本格的に学習して7ヶ月目に入りました。PHP,Laravelを学習しポートフォリオを作成中です。前回、投稿画面にGoogle Maps APIを埋め込む手続きを行いました。ディレクトリ構成が良くなく、うまく表示できない問題があり、今回改善を行いました。

概要

Laravel Sailを使った開発環境で、Google Maps APIを利用して地図を描画しました。
今回はディレクトリ構成を変更したことで、地図機能が大幅に改善された内容を記載します。
具体的な問題点とポイントは以下になります。

1. viewファイル内に直接JavaScriptを記載していた
2. Viewファイル毎にJSを作成し、Viewファイルはscriptの読み込みだけにした

Google Maps API導入の簡単な手順については、前回の投稿に記載しております。

viewファイル内に直接JavaScriptを記載していた

記事を投稿するviewページに地図を表示させる際、そのviewファイル内にJSを記載していた。
最初は動いていたが、投稿詳細ページで再度地図を表示させる際に、エラーが発生。
ディレクトリ構成を見直した。

Viewファイル毎にJSを作成し、Viewファイルはscriptの読み込みだけにした

Viewファイル内には、JSを直接記載せず、JSファイルを別に作成
以下がディレクトリ内容です。

Viewファイル(create.blade.php)

<x-app-layout>
    <div class="max-w-3xl mx-auto p-6 bg-blue-100 shadow-md rounded-lg">
        <h2 class="text-3xl font-bold mb-6 text-center">新規投稿</h2>
        <form method="POST" action="{{ route('posts.store') }}" id="postForm" class="pb-20">
            @csrf
            <!-- タイトル -->
            <div class="mb-6">
                <label for="title" class="block text-lg font-medium text-gray-700">タイトル</label>
                <input type="text" id="title" name="title" required
                    class="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200">
            </div>

            <!-- 地図表示 -->
            <div id="map" class="w-full h-64 mb-4"></div>

            <!-- 緯度と経度 (hidden) -->
            <input type="hidden" id="latitude" name="latitude">
            <input type="hidden" id="longitude" name="longitude">

            <!-- 投稿ボタン -->
            <div class="text-center">
                <button type="submit"
                    class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-md">
                    投稿する
                </button>
            </div>
        </form>
    </div>

// 当初はこの部分にJavaScriptを直接記載していた 
    <!-- create.js を読み込む -->
    <script type="module" src="{{ mix('resources/js/create.js') }}"></script>


</x-app-layout>

JSファイル(create.js)

import { Loader } from "@googlemaps/js-api-loader";

const loader = new Loader({
    apiKey: import.meta.env.VITE_GOOGLE_MAPS_API_KEY, // Google Maps APIキー
    libraries: ["places"], // 必要なライブラリ
});

loader.load().then(() => {
    const mapElement = document.getElementById("map");
    if (!mapElement) return; // 地図要素がない場合は終了

    const geocoder = new google.maps.Geocoder();
    const map = new google.maps.Map(mapElement, {
        center: { lat: 35.6895, lng: 139.6917 }, // 東京の初期位置
        zoom: 15,
    });

    let marker = null;

    document.getElementById("search-location").addEventListener("click", () => {
        const address = document.getElementById("location_name").value;
        if (!address) {
            alert("住所を入力してください。");
            return;
        }

        geocoder.geocode({ address: address }, (results, status) => {
            if (status === "OK" && results.length > 0) {
                const location = results[0].geometry.location;

                map.setCenter(location);

                if (marker) marker.setMap(null);
                marker = new google.maps.Marker({
                    map,
                    position: location,
                });

                document.getElementById("latitude").value = location.lat();
                document.getElementById("longitude").value = location.lng();
            } else {
                alert("住所の検索に失敗しました: " + status);
            }
        });
    });
});

最終的な成果

以下のことが実現できました:

  • 新規投稿のviewファイル用のJSと投稿詳細表示用のviewファイル用のJSを分割
  • 分割することで、コードを修正する時に作業が容易になった
  • JSの読み込み元が明確になり、正しく地図情報が表示されるようになった

最後まで、ご視聴頂きありがとうございます。

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?