0

我正在尝试使用谷歌地图 API 和 heatmaps.js 创建一个有 2 层的热图。我可以通过硬编码我的纬度/经度变量来创建我的地图,但最终我希望我的图层从可以轻松刷新的 JSON 文件中提供。

这是我当前的 HTML,效果很好。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href='css/bootstrap.css' rel='stylesheet' type='text/css'></link>
    <link href='css/bootstrap-responsive.css' rel='stylesheet' type='text/css'></link>

    <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
    <script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization&.js"></script>

    <style type="text/css">
      body {
        padding-top: 60px;
        padding-bottom: 40px;
      }
      .sidebar-nav {
        padding: 9px 0;
      }

      @media (max-width: 980px) {
        /* Enable use of floated navbar text */
        .navbar-text.pull-right {
          float: none;
          padding-left: 5px;
          padding-right: 5px;
        }
      }
    </style>

    <script>
      var map, pointarray, heatmap;

      var layer1 = [
        {location: new google.maps.LatLng(42.071523,-72.624257), weight:13.747727085},
        {location: new google.maps.LatLng(42.37686,-72.46914), weight:6.6332495807},
        {location: new google.maps.LatLng(42.40524,-72.528427), weight:5.1961524227},
        {location: new google.maps.LatLng(42.383945,-72.511834), weight:1.7320508076},
        {location: new google.maps.LatLng(42.433317,-72.114488), weight:5.6568542495}
      ];

      var layer2 = [
        {location: new google.maps.LatLng(41.513113,-74.37616), weight:2.4494897428},
        {location: new google.maps.LatLng(41.147711,-73.941171), weight:10},
        {location: new google.maps.LatLng(41.329376,-74.347207), weight:4.8989794856},
        {location: new google.maps.LatLng(41.338977,-73.987248), weight:1.7320508076}
      ];


      function initialize() {
        var mapOptions = {
          zoom: 4,
          center: new google.maps.LatLng(38.82, -99.408660),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);

        pointArray1 = new google.maps.MVCArray(layer1);
        pointArray2 = new google.maps.MVCArray(layer2);

        heatmap1 = new google.maps.visualization.HeatmapLayer({
          data: pointArray1
        });
        heatmap2 = new google.maps.visualization.HeatmapLayer({
          data: pointArray2
        });

        heatmap1.setMap(map);
        heatmap2.setMap(map);
      }

    //FUNCTION TO CHANGE LAYERS
    function changeMap(layerNum) {

    if (layerNum == 1) {
    updateMap(heatmap1);
    }
    if (layerNum == 2) {
    updateMap(heatmap2);
    }
    }

    //FUNCTION TO UPDATE LAYERS
    function updateMap(layer) {
       var layerMap = layer.getMap();
       if (layerMap) {
          layer.setMap(null);
       } else {
          layer.setMap(map);
       }
    } 
    </script>

    <link href='css/DT_bootstrap.css' rel='stylesheet' type='text/css'></link>

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->

 </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="#">Test Page</a>
          <div class="nav-collapse collapse">
            <p class="navbar-text pull-right">
              Logged in as <a href="#" class="navbar-link">...</a>
            </p>
            <ul class="nav">
              <li class="active"><a href="index.html">Home</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

<body class="container-fluid">
    <div class="row">
        <div class="span12" style="float: none; margin: 0 auto;">
          <body onload="initialize()">
          <h3>Test Layers</h3>
            <input type='checkbox' name='system_type17' value='1' onclick="changeMap(this.value);" checked="checked" />
            <span style="width:100px;display:inline-block;">Layer 1</span>
            <input type="checkbox" name="system_type3" value="2" onclick="changeMap(this.value);" checked="checked" />
            <span style="width:100px;display:inline-block;">Layer 2</span>
            <br><br/>
            <div id="map-canvas" style="height: 575px; width: 1000px;"></div>
          </body>
        </div>
    </div>
</body>

  </body>
</html>

我想做的是用我可以查询的单个 JSON 文件替换 var layer1 和 layer2,我只是不确定如何执行这样的事情。例如,一个看起来像这样的 JSON 文件:

{
    "datapoints": [
        {
            "lat": "38.1513366000",
            "lon": "-97.4341659000",
            "weight": "0",
            "layer":"1"
        },
        {
            "lat": "38.1513748000",
            "lon": "-97.4341125000",
            "weight": "0",
            "layer":"1"
        },
        {
            "lat": "38.1513938000",
            "lon": "-97.4341125000",
            "weight": "0",
            "layer":"1"
        },
        {
            "lat": "38.1493263000",
            "lon": "-97.4339447000",
            "weight": "0",
            "layer":"1"
        },
        {
            "lat": "38.1493339000",
            "lon": "-97.4339447000",
            "weight": "0",
        "layer":"2"
        },
        {
            "lat": "38.1493377000",
            "lon": "-97.4339447000",
            "weight": "0",
            "layer":"2"
        },
        {
            "lat": "38.1483650000",
            "lon": "-97.4358291000",
            "weight": "0",
            "layer":"2"
        },
        {
            "lat": "38.1484031000",
            "lon": "-97.4358062000",
            "weight": "0",
            "layer":"2"
        }
    ]
}

根据 Yehia 的建议更新代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href='css/bootstrap.css' rel='stylesheet' type='text/css'></link>
    <link href='css/bootstrap-responsive.css' rel='stylesheet' type='text/css'></link>

    <script type='text/javascript' src='js/jquery-1.8.3.js'></script>
    <script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization&.js"></script>

    <style type="text/css">
      body {
        padding-top: 60px;
        padding-bottom: 40px;
      }
      .sidebar-nav {
        padding: 9px 0;
      }

      @media (max-width: 980px) {
        /* Enable use of floated navbar text */
        .navbar-text.pull-right {
          float: none;
          padding-left: 5px;
          padding-right: 5px;
        }
      }
    </style>

    <script>
      var map, pointarray, heatmap;

      /*var layer1 = [
        {location: new google.maps.LatLng(42.071523,-72.624257), weight:13.747727085},
        {location: new google.maps.LatLng(42.37686,-72.46914), weight:6.6332495807},
        {location: new google.maps.LatLng(42.40524,-72.528427), weight:5.1961524227},
        {location: new google.maps.LatLng(42.383945,-72.511834), weight:1.7320508076},
        {location: new google.maps.LatLng(42.433317,-72.114488), weight:5.6568542495}
      ];

      var layer2 = [
        {location: new google.maps.LatLng(41.513113,-74.37616), weight:2.4494897428},
        {location: new google.maps.LatLng(41.147711,-73.941171), weight:10},
        {location: new google.maps.LatLng(41.329376,-74.347207), weight:4.8989794856},
        {location: new google.maps.LatLng(41.338977,-73.987248), weight:1.7320508076}
      ];*/

      function initialize() {
        var mapOptions = {
          zoom: 4,
          center: new google.maps.LatLng(38.82, -99.408660),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
      }

    //FUNCTION TO CHANGE LAYERS
    function changeMap(layerNum) {

    if (layerNum == 1) {
    updateMap(heatmap1);
    }
    if (layerNum == 2) {
    updateMap(heatmap2);
    }
    }

    //FUNCTION TO UPDATE LAYERS
    function updateMap(layer) {
       var layerMap = layer.getMap();
       if (layerMap) {
          layer.setMap(null);
       } else {
          layer.setMap(map);
       }
    } 
    </script>

    <link href='css/DT_bootstrap.css' rel='stylesheet' type='text/css'></link>

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->

 </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="#">Test Page</a>
          <div class="nav-collapse collapse">
            <p class="navbar-text pull-right">
              Logged in as <a href="#" class="navbar-link">...</a>
            </p>
            <ul class="nav">
              <li class="active"><a href="index.html">Home</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

<body class="container-fluid">
    <div class="row">
        <div class="span12" style="float: none; margin: 0 auto;">
          <body onload="initialize()">
          <h3>Test Layers</h3>
            <input type='checkbox' name='system_type17' value='1' onclick="changeMap(this.value);" checked="checked" />
            <span style="width:100px;display:inline-block;">Layer 1</span>
            <input type="checkbox" name="system_type3" value="2" onclick="changeMap(this.value);" checked="checked" />
            <span style="width:100px;display:inline-block;">Layer 2</span>
            <br><br/>
            <div id="map-canvas" style="height: 575px; width: 1000px;"></div>
          </body>
        </div>
    </div>
      <script type="text/javascript">
        $.getJSON("testdata.json").then(function(data) {
              $.each(data, function(i,datapoints) {
                $.each(datapoints, function(j,datapoint) {
                  layers.push({
                    location: new google.maps.LatLng(datapoint.lat, datapoint.lng),
                    weight: datapoint.weight,
                    layerID: datapoint.layer
                  });
                });
              });
            });
    <script>
</body>

  </body>
</html>

好吧,我想差不多了。非常感谢您到目前为止的帮助,我知道这很痛苦。这是我的初始化函数,我仍然收到 Uncaught ReferenceError: layers is not defined

<script type='text/javascript'>
      var map, pointarray, heatmap;

      function initialize() {

            function loadData() {
            var layers = [ ];
            $.ajax({
              url: 'testdata.json',
              async: false,
              dataType: 'json',
              success: function (data) {
                for (var i=0; i<data.datapoints.length; i++) {
                  var datapoint = data.datapoints[i];
                  if (layers[datapoint.layer]===undefined) {
                    layers[datapoint.layer] = [];
                  }
                  layers[datapoint.layer].push({
                    location: new google.maps.LatLng(datapoint.lat, datapoint.lon),
                    weight: datapoint.weight,
                    layerID: datapoint.layer
                  });
                }
              }
            });
            return layers;
          }
        var mapOptions = {
          zoom: 4,
          center: new google.maps.LatLng(38.82, -99.408660),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);

        pointArray1 = new google.maps.MVCArray(layers[1]);
        pointArray2 = new google.maps.MVCArray(layers[2]);

        heatmap1 = new google.maps.visualization.HeatmapLayer({
          data: pointArray1
        });
        heatmap2 = new google.maps.visualization.HeatmapLayer({
          data: pointArray2
        });

        heatmap1.setMap(map);
        heatmap2.setMap(map);
      }

    //FUNCTION TO CHANGE LAYERS
    function changeMap(layerNum) {

    if (layerNum == 1) {
    updateMap(heatmap1);
    }
    if (layerNum == 2) {
    updateMap(heatmap2);
    }
    }

    //FUNCTION TO UPDATE LAYERS
    function updateMap(layer) {
       var layerMap = layer.getMap();
       if (layerMap) {
          layer.setMap(null);
       } else {
          layer.setMap(map);
       }
    } 
    </script>
4

1 回答 1

0

您需要一种读取 JSON 并将其解析为所需变量的方法。由于您使用的是 jQuery,因此这里有一个适用于您拥有的 JSON 结构的方法。

$.getJSON("layers.json").then(function(data) {
      $.each(data, function(i,datapoints) {
        $.each(datapoints, function(j,datapoint) {
          layers.push({
            location: new google.maps.LatLng(datapoint.lat, datapoint.lng),
            weight: datapoint.weight,
            layerID: datapoint.layer
          });
        });
      });
    });

根据需要进行调整。

为了响应 davids12 的更新,这里有一个函数,它返回一个数组数组,其中每个复合数组都有来自某个层的数据点。因此,运行您的示例,layers其中将有 2 个数组(layers[1]和) ,layers[2]它们基本上是您在代码中描述的(带有一个附加变量;如果您愿意,可以将其删除)。这允许您通过使用您现在拥有的格式将它们放入 JSON 中来加载更多的层和点。layer1layer2layerID

  function loadData() {
    var layers = [ ];
    $.ajax({
      url: 'j.json',
      async: false,
      dataType: 'json',
      success: function (data) {
        for (var i=0; i<data.datapoints.length; i++) {
          var datapoint = data.datapoints[i];
          if (layers[datapoint.layer]===undefined) {
            layers[datapoint.layer] = [];
          }
          layers[datapoint.layer].push({
            location: new google.maps.LatLng(datapoint.lat, datapoint.lng),
            weight: datapoint.weight,
            layerID: datapoint.layer
          });
        }
      }
    });
    return layers;
  }
于 2013-04-24T23:26:24.583 回答