勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

Google Maps APIでヒートマップを表示する方法

   2024/01/13  Google Maps API Google

Google Maps APIで花粉状況や雨量を可視化しやすいようなヒートマップ的なものを表示したかった。調べてみるとAPIで提供されている模様。以下にサンプルとソース。

 

サンプル

https://taitan916.info/sample/heatmap/

 

ソース

//サンプルマップ作成。東京タワーを中心地に指定
var currentWindow = null;
var sample = { 'x':'35.65858', 'y':'139.745433'};
var latlng = new google.maps.LatLng(sample.x, sample.y);
var myOptions = { zoom: 12, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

//ヒートマップ用のサンプルデータの作成
var data = [
    {"surveyedPrice":1,pos:[139.745433,35.65858]}, //東京タワー
    {"surveyedPrice":2,pos:[139.73000000000002,35.66]}, //六本木ヒルズ
    {"surveyedPrice":3,pos:[139.76608399999998,35.681382]}, //東京駅
    {"surveyedPrice":3,pos:[139.68967299999997,35.758669]} //ときわ台
];
var bounds = new google.maps.LatLngBounds();
var pos, populations = [];
for (var i=0; i < data.length; i++) {
    pos = new google.maps.LatLng(data[i].pos[1], data[i].pos[0]);
    populations.push({
        location : pos,
        weight : data[i].surveyedPrice //ヒートマップの重み付けに使用するデータを指定
    })
    bounds.extend(pos); 
}

//ヒートマップレイヤの作成
var heatmap = new google.maps.visualization.HeatmapLayer({
    radius:50 //ヒートマップの各ポイントの大きさ
});

//ヒートマップレイヤをマップに表示
heatmap.setData(populations);
heatmap.setMap(map);

 

注意点

マップのAPIを呼び出す際にlibraries=visualizationのクエリが必要。以下のような形で呼び出す。

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true&libraries=visualization"></script>

 - Google Maps API Google

  関連記事

HTML5のGeolocation APIで位置情報を取得してGoogleMapAPIで使用する方法

GPSみたいな位置情報を取得しGoogleMapAPIでその場所を反映させたかっ ...

Google Maps APIで都道府県の中心地と県庁所在地にマーカーを立てる方法

Google Maps APIで都道府県の中心地もしくは県庁所在地にマーカーを立 ...

Google Maps APIで住所から経度緯度を取得する方法

やりたかった事はformに住所を入れてsubmitする際に、javascript ...

Google Maps APIで複数のマーカーをまとめる方法

Google Maps APIでマーカーを複数表示し、近隣のエリアごとにまとめて ...

GoogleMapAPIで住所・経度緯度入力後にマーカーを移動させる

フォーム内に住所・経度・緯度のテキストボックスを設置し、住所を入力後にボタンを押 ...