スクリプトを外部ファイルに分ける

広告

Google Maps APIを使用することで、単にWebページ上に地図を表示するだけでなくマーカーを設置したり地図上でクリックされた時に独自の処理を行ったりといったことが可能になります。これらの機能を実現するために独自のスクリプトを追加していくことになるのですが、あまりWebページに長文のスクリプトを記述すると可読性が悪くなる場合があります。そこでこのページではスクリプトを外部ファイルに分けて記述す方法について解説します。

1.スクリプトを外部ファイルとして用意する
2.サンプルコード

スクリプトを外部ファイルとして用意する

前のページで作成した次のHTMLページを例に試してみます。今回外部ファイルとして分離するのは次の部分です。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Google Maps API サンプル</title>
  </head>
  <body>
    <p>自宅の地図です。</p>

    <div id="map" style="width:620px; height:400px"></div>

    <script type="text/javascript">
    function initMap() {
      var opts = {
        zoom: 15,
        center: new google.maps.LatLng(35.1239654, 136.9417741)
      };
      var map = new google.maps.Map(document.getElementById("map"), opts);
    }
    </script>

    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=APIKey&callback=initMap">
    </script>
  </body>
</html>

テキストエディタを使って先ほどの部分だけを記述したファイルを作成します。今回ファイル名は「sample.js」としました。

function initMap() {
  var opts = {
    zoom: 15,
    center: new google.maps.LatLng(35.1239654, 136.9417741)
  };
  var map = new google.maps.Map(document.getElementById("map"), opts);
}

次にWebページから先ほど作成したsample.jsファイルを読み込むように記述します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Google Maps API サンプル</title>
  </head>
  <body>
    <p>自宅の地図です。</p>

    <div id="map" style="width:620px; height:400px"></div>

    <script type="text/javascript" src="sample.js">
    </script>

    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=APIKey&callback=initMap">
    </script>
  </body>
</html>

このようにGoogle Maps APIに関するスクリプトを別ファイルに分離し、元のWebページからその分離したファイルを読み込んで利用することができます。

サンプルコード

では簡単なサンプルを作成して実際に試してみます。下記のサンプルでは独自コードの部分を外部ファイルに分離しています。

function initMap() {
  var opts = {
    zoom: 15,
    center: new google.maps.LatLng(35.1253694,136.9073667)
  };
  var map = new google.maps.Map(document.getElementById("map"), opts);
}
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Google Maps API サンプル</title>
  </head>
  <body>
    <p>熱田神宮です。</p>

    <div id="map" style="width:620px; height:400px"></div>

    <script type="text/javascript" src="code2_1.js">
    </script>

    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=APIKey&callback=initMap">
    </script>
  </body>
</html>

ブラウザでWebページを開くと次のように表示されます。

p2-1

今後作成するGoogle Maps API用のスクリプトについては基本的に外部ファイルに記述するようにします。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。