地図にデータをインポートする

概要

ローカルまたはリモートのソースから GeoJSON データをインポートし、地図に表示する方法を説明します。このチュートリアルでは、以下の地図を使用して、データを地図にインポートするさまざまな方法を説明します。

以下のセクションに、このチュートリアルでマップを作成するために必要なコード全体を載せています。

TypeScript

let map: google.maps.Map;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: "terrain",
  });

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results: any) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

declare global {
  interface Window {
    initMap: () => void;
    eqfeed_callback: (results: any) => void;
  }
}
window.initMap = initMap;
window.eqfeed_callback = eqfeed_callback;

JavaScript

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: "terrain",
  });

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

window.initMap = initMap;
window.eqfeed_callback = eqfeed_callback;

CSS

/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
#map {
  height: 100%;
}

/*
 * Optional: Makes the sample page fill the window.
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

HTML

<html>
  <head>
    <title>Earthquake Markers</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!--
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

サンプルを試す

データを読み込む

このセクションでは、Maps JavaScript API アプリケーションと同じドメインから、または別のドメインからデータを読み込む方法について説明します。

同じドメインからデータを読み込む

Google Maps データレイヤーは、任意の地理空間データ(GeoJSON を含む)のコンテナを提供します。Maps JavaScript API アプリケーションと同じドメインにホストしているファイルにデータが存在する場合は、map.data.loadGeoJson() メソッドを使用してデータを読み込むことができます。このファイルは同じドメインに存在する必要がありますが、別のサブドメインでホストできます。たとえば、www.example.com から files.example.com にリクエストを送信できます。

map.data.loadGeoJson('data.json');

ドメインをまたいでデータを読み込む

ドメインの設定で許可されていれば、自己所有のドメイン以外のドメインに対してデータをリクエストすることもできます。こうした権限の標準は、クロスオリジン リソース シェアリング(CORS)と呼ばれます。ドメインでクロスドメイン リクエストを許可している場合は、レスポンスのヘッダーに次の宣言を含める必要があります。

Access-Control-Allow-Origin: *

ドメインで CORS が有効になっているかどうかを確認するには、Chrome デベロッパー ツール(DevTools)を使用します。

このようなドメインからのデータの読み込みは、同じドメインから JSON を読み込む場合と同じです。

map.data.loadGeoJson('http://www.CORS-ENABLED-SITE.com/data.json');

JSONP のリクエスト

この手法を使用するには、対象のドメインで JSONP のリクエストがサポートされている必要があります。

JSONP をリクエストする場合は、createElement() を使用して、ドキュメントのヘッダーに script タグを追加します。

var script = document.createElement('script');
script.src = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);

スクリプトを実行すると、対象のドメインは引数として別のスクリプト(通常は callback() という名前)に渡します。対象のドメインは、コールバック スクリプトの名前を定義します。これは、ブラウザで対象の URL を読み込むと、最初にページに表示される名前です。

たとえば、ブラウザのウィンドウで http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp を読み込むと、コールバックの名前が eqfeed_callback であることがわかります。

コールバック スクリプトをコード内で定義する必要があります。

function eqfeed_callback(response) {
  map.data.addGeoJson(response);
}

addGeoJson() メソッドを使用して、解析された GeoJSON データを地図に配置します。

データのスタイル設定

データの外観を変更するには、GeoJSON データを Map オブジェクトに追加します。データのスタイル設定について詳しくは、デベロッパー ガイドをご覧ください。

詳細

  • GeoJSON は、JSON(JavaScript Object Notation)を基にしたオープンなフォーマットで、地理情報データのエンコードに幅広く使用されています。JSON データ用に設計された JavaScript のツールやメソッドも GeoJSON にも使用できます。詳しくは、デベロッパー ガイドをご覧ください。
  • JSONP は padded JSON の略です。これは、別のドメインにあるサーバーにデータをリクエストするため、ウェブブラウザで実行される JavaScript プログラムで使用される通信メソッドです。