PR

【WordPress】Google Maps APIを使って地図に円を描いて表示するサンプルコード

Google Maps APIを使って円を描いた地図をWordPressの記事に表示するサンプルコードについて説明する

WordPress:v6.1.1
使用テーマ:Cocoon

スポンサーリンク

はじめに

Google Maps APIを使って円を描いた地図をWordPressの記事に表示するサンプルコードについて説明する

↓公式ドキュメントはこちら

Google Maps Platform のドキュメント  |  Maps JavaScript API  |  Google for Developers
Google Maps Platform のドキュメント

↓Google Maps APIを使用するために必要なAPIキーの取得はこちら(無料)

Google Cloud プロジェクトをセットアップする  |  Maps JavaScript API  |  Google for Developers
API キーを使用する  |  Maps JavaScript API  |  Google for Developers

カスタムHTMLブロックで地図を表示する

Google Maps APIを使って円を描いた地図は「カスタムHTML」ブロックを使うことでWordPressの記事に埋め込むことができる

カスタム HTML
HTML (Hypertext Markup Language) は、ウェブページの意味的な内容を記述するため…
Simple Map  |  Maps JavaScript API  |  Google for Developers

上記の地図を表示するためのカスタムHTMLはこれ

<div id="map"></div>

<style type="text/css">
#map{margin: 0px auto;}
</style>

<script type="text/javascript">
const citymap = {
  chicago: {
    center: { lat: 41.878, lng: -87.629 },
    population: 2714856,
  },
  newyork: {
    center: { lat: 40.714, lng: -74.005 },
    population: 8405837,
  },
  losangeles: {
    center: { lat: 34.052, lng: -118.243 },
    population: 3857799,
  },
  vancouver: {
    center: { lat: 49.25, lng: -123.1 },
    population: 603502,
  },
};

function initMap() {
  // Create the map.
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: 37.09, lng: -95.712 },
    mapTypeId: "terrain",
  });

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (const city in citymap) {
    // Add the circle for this city to the map.
    const cityCircle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100,
    });
  }
}
</script>

<script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;callback=initMap">
</script>

YOUR_API_KEYの部分には自身のAPIキーを入力する

↓APIキーは[Google Maps Platform] > [認証情報] ページで確認できる

Google Cloud プラットフォーム
Google Cloud Platform では、Google と同じインフラストラクチャでアプリケーション、ウェブサイト、サービスを構築、導入、拡大することができます。

new google.maps.Circle()の設定項目は以下の通り

strokeColor#FF0000線の色
strokeOpacity0.8線の透明度
strokeWeight2線の太さ
fillColor#FF0000塗りつぶしの色
fillOpacity0.35塗りつぶしの透明度
center{ lat: 40.714, lng: -74.005 }円の中心座標
radiusMath.sqrt(8405837)*100円の半径 [m]
例)Newyork

↓参考

≫【APIキー】【要確認】Google Maps Platform APIキーの取得方法と注意点
≫【CSS】text-align: center, margin 0 auto〜左右中央寄せする二つの方法
≫【CSS】CSSのidとclassの使い分け
≫【Javascript】Google Maps APIを使ったページの基本構成

おわりに

Google Maps APIを使って円を描いた地図をWordPressの記事に表示するサンプルコードについて説明した

↓関連記事

コメント