1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Maps API × Vite × Javascript で google is not defined にハマった話

Posted at

Laravel + Vite 環境で Google Maps API を使っていたところ、
ローカルや本番で次のようなエラーに悩まされました。

Uncaught ReferenceError: google is not defined

環境

Laravel 12.21.0
Vite ^7.0.4
Google Maps JavaScript API
JSは ES Modules で管理

発生していたエラー

google is not defined
Google Maps API not loaded
InvalidValueError: initMap is not a function

原因の結論

Google Maps API が読み込まれる前に google.maps を使っていた

NG

const tokyoStation = { lat: 35.681236, lng: 139.767125 };
const googleMap = createMap(tokyoStation); 

document.addEventListener('DOMContentLoaded', () => {
  
  〜 メインのコード 〜
  
});

function createMap(center) {
 // google map apiを呼び込む
  return new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center,
  });
}

① HTML を読む
② DOM を作る
③ DOMContentLoaded 発火
④ Google Maps API をネットから取得
⑤ Google Maps API 読み込み完了
⑥ window.initMap が呼ばれる
という順番なので
createMapをapi取得前に呼び込んでいるのが原因

解決したコード

window.initMap = ()=> {
    const tokyoStation = { lat: 35.681236, lng: 139.767125 };
    googleMapInstance = createMap(tokyoStation);

    ~ メインコード ~
};

function createMap(center) {
 // google map apiを呼び込む
  return new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center,
  });
}

windowを挟むことで、google map apiが読み込まれるのを待つことで解決

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?