0

Google Map APIをビューで表示させたい

開発環境

  • AWS Amazon Linux2
  • PHP8 Laravel

質問内容

  • API KEYを取得し、.envに記述、その後ビューにてmapを表示させたいが全く表示されないのでどこがおかしいのかご意見頂けませんか??

ソースコード

  • resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>{{ config('app.name', 'CLOUD SHARE') }}</title>

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

        <!-- Scripts -->
        @vite(['resources/css/app.css', 'resources/js/app.js'])

    </head>
    <body class="font-sans antialiased">
        <div class="min-h-screen bg-gray-100">
            @include('layouts.navigation')

            <!-- Page Content -->
            <main>
                @if (session('status'))
                    <div class="text-green-500 px-4 py-2 rounded">
                        {{ session('status') }}
                    </div>
                @endif
                @if (session('message'))
                    <div class="text-green-500 px-4 py-2 rounded">
                        {{ session('message') }}
                    </div>
                @endif
                @yield('content')
            </main>
        </div>
    <script src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&callback=initMap" async defer></script>
    </body>
</html>

mapを表示させたいビュー

  • resources/views/layouts/user/show.blade.php
@extends('layouts.app')

@section('content')

<!--<写真の位置情報をJavaScriptオブジェクトとして作成 -->
<script>
let locations = [
    @foreach($photos as $photo)
    { "id": "{{ $photo->id }}", "lat": {{ $photo->latitude }}, "lng": {{ $photo->longitude }} },
    @endforeach
];
</script>

<section class="text-gray-600 body-font">
  <div class="container px-5 py-24 mx-auto">
    <div class="flex flex-col text-center mb-20">
      <h1 class="text-2xl font-medium title-font mb-4 text-gray-900">{{ $user->name }}さんの投稿</h1>
      <!--<p class="lg:w-2/3 mx-auto leading-relaxed text-base">Whatever cardigan tote bag tumblr hexagon brooklyn asymmetrical gentrify, subway tile poke farm-to-table. Franzen you probably haven't heard of them.</p>-->
    </div>
    <div class="flex flex-wrap -m-4">
       @foreach($photos as $photo)
         <div class="p-4 lg:w-1/4 md:w-1/2">
           <div class="h-full flex flex-col items-center text-center">
             <img alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{ Storage::url($photo->filename )}}" style="object-fit: cover; width: 200px; height:200px;">
             <div id="map-{{ $photo->id }}" style="height: 200px; width: 100%;"></div>

             <div class="w-full">
               <h2 class="title-font font-medium text-lg text-gray-900">タイトル: {{ $photo->title }}</h2>
               <h3 class="text-gray-500 mb-3">名前: {{ $user->name }}</h3>
               <p class="mb-4">{{ $photo->caption }}</p>

               <form method="POST" action="{{ route('photo.destroy', ['id' => $photo->id]) }}">
                   @csrf
                   @method('DELETE')

               @if(Auth::user()->id == $photo->user_id)
                   <button type="submit" class="btn btn-danger bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded" onclick="return confirm('本当に削除しますか')">
                       削除
                   </button>
               @endif
               </form>

               <form method="GET" action="{{ route('photo.edit', ['photo' => $photo->id]) }}">
                   @csrf
                   @method('GET')

               @if(Auth::user()->id == $photo->user_id)
                   <button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded">
                       編集
                   </button>
               @endif
               </form>
             </div>
           </div>
         </div>
       @endforeach
    </div>

    <!-- APIの読み込みと初期化は一度だけ行う -->
    <script src="{{ asset('/js/result.js') }}"></script>



  </div>
</section>

@endsection

JavaScript

  • public/js/result.js
let locations = []; 

function initAllMaps() {
    for (let location of locations) {
        initMap(location.id, location.lat, location.lng);
    }
}

function initMap(id, lat, lng) {
    let mapElement = document.getElementById("map-" + id);
    let location = {lat: lat, lng: lng};

    let map = new google.maps.Map(mapElement, {
        zoom: 13,
        center: location
    });

    let marker = new google.maps.Marker({
        position: location,
        map: map,
        title: 'Location'
    });
}

実際の画面

1
  • 最後に掲載されている画像を見る限りではJavaScriptの処理上の問題の可能性が高いため、まずは「Laravelが生成したHTMLが正しい内容になっているか」を見る必要があります。目的とコードから推測する範囲では、show.blade.php内<script>タグ内の記述上の問題か$photoのあ使い方の問題な気がしますが。
    – attakei
    7月12日 13:32

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。