MacOSで
PHP 7.4.1
Laravel 8.75
を使用しています。Laravel8でMaps JavaScript API(Google Map API)を使用した際にresourses/js/result.jsをlaravel-mixで使用するとエラーが出てしまいました。この前段階として
public/js/result.jsにJSを記述し、laravel-mixを使わないで試したところうまく行っていたので次にlaravel-mixを使用してresourses/js/result.js内の関数をviewで読み込もうという考えでした。
コード (プロジェクト名) ├─ resourses │ ├─ js │ │ └─ result.js(これをlaravel-mixで) │ └─ app.js │ ├─ views │ └─ welcome.blade.php(表示画面) │ ├─ public │ └─ js/result.js(成功後、resourses/jsにコピーして消去) │ │
public/js/result.jsの場合のweb上での画面
welcome.blade.php
コード <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> Where is Tokyo Tower ? </head> <body> <div id="map" style="height:500px"> </div> {{-- <script src="{{ asset('/js/result.js') }}"></script> --}} <script src="{{ mix('js/result.js') }}" defer></script> <script src="https://maps.googleapis.com/maps/api/js?language=ja®ion=JP&key={{ env('GCP_API')}}&callback=initMap" async defer> </script> </body> </html>
webpack-mix.js
コード const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .js('resources/js/result.js', 'public/js') .version();
resourses/js/result.js
コード // googleMapsAPIを持ってくるときに,callback=initMapと記述しているため、initMap関数を作成 function initMap() { // welcome.blade.phpで描画領域を設定するときに、id=mapとしたため、その領域を取得し、mapに格納します。 map = document.getElementById("map"); // 東京タワーの緯度は35.6585769,経度は139.7454506と事前に調べておいた let tokyoTower = {lat: 35.6585769, lng: 139.7454506}; // オプションを設定 opt = { zoom: 13, //地図の縮尺を指定 center: tokyoTower, //センターを東京タワーに指定 }; // 地図のインスタンスを作成します。第一引数にはマップを描画する領域、第二引数にはオプションを指定 mapObj = new google.maps.Map(map, opt); marker = new google.maps.Marker({ // ピンを差す位置を決めます。 position: tokyoTower, // ピンを差すマップを決めます。 map: mapObj, // ホバーしたときに「tokyotower」と表示されるようにします。 title: 'tokyotower', }); }
エラーは
コード 127.0.0.1/:1 Uncaught (in promise) ne {message: 'initMap is not a function', name: 'InvalidValueError', stack: 'Error\n at new ne (https://maps.googleapis.com/m…r7EqxPk&callback=initMap:197:124'} message: "initMap is not a function" name: "InvalidValueError" stack: "Error\n at new ne (https://maps.googleapis.com/maps/api/js?language=ja®ion=JP&key=AIztPk&callback=initMap:66:280)\n at Object._.pe (https://maps.googleapis.com/maps/api/js?language=ja®ion=JP&key=AIH_8MztPk&callback=initMap:66:391)\n at Bea (https://maps.googleapis.com/maps/api/js?language=ja®ion=JP&key=AzaPk&callback=initMap:197:241)\n at https://maps.googleapis.com/maps/api/js?language=ja®ion=JP&key=APk&callback=initMap:197:124" [[Prototype]]: Error
initMap is not a functionだったり、 welcome.blade.phpの方では <script src="https://maps.googleapis.com®ion=JP&key={{ env('GCP_API')}}&callback=initMap" async defer> なのに initMap:197:124' のような:197:124'が何故かついている
ことから、うまくlaravel-mixが機能していないと思われます。ですが、具体的な原因がわからないでいます。よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/03/23 23:11