【问题标题】:how to get google heat map LatLng with JSON?如何使用 JSON 获取谷歌热图 LatLng?
【发布时间】:2018-06-30 05:20:01
【问题描述】:

我想用 Json 文件获取 google heat map LatLng

这是我的谷歌热图功能

 function initMap() {

        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 11,
            center: {lat: 37.782551, lng: -122.445368}
        });

        heatmap = new google.maps.visualization.HeatmapLayer({
            data: getPoints(),
            map: map
        });

    }


这是我的 LatLng 函数,我想改用 getPoints() 函数 JSON 文件

function getPoints() {
        return [
        new google.maps.LatLng(37.782551, -122.445368),
        new google.maps.LatLng(37.782745, -122.444586),
        new google.maps.LatLng(37.782842, -122.443688),
        new google.maps.LatLng(37.782919, -122.442815),
        new google.maps.LatLng(37.782992, -122.442112),
}

【问题讨论】:

标签: javascript json google-maps heatmap


【解决方案1】:

假设您创建了一个名为 points.json 的文件,该文件如下所示,并且与您的网页的 HTML 位于同一目录中。

{
  "points": [
    [37.782551, -122.445368],
    [37.782745, -122.444586],
    [37.782842, -122.443688],
    [37.782919, -122.442815],
    [37.782992, -122.442112]
  ]
}

然后您需要从网络服务器请求 JSON 文件。如果您可以使用最近的网络浏览器,您可以使用fetch

function requestPoints() {
  fetch('points.json')
    .then(function(response) {
      return response.json();
    })
    .then(initMap);
}

如果你不能使用最近的网络浏览器,那么你可以用jQuery.getJSON做类似的事情。

当“points.json”的网络请求返回时,这将使用 JSON 调用 initMap。然后你可以像这样使用 JSON:

function initMap(json) {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {lat: 37.782551, lng: -122.445368}
  });

  var points = json.points;
  var data = [];
  var i;
  for (i = 0; i < points.length; i++) {
    data[i] = new google.maps.LatLng(points[i][0], points[i][1]);
  }

  var heatmap = new google.maps.visualization.HeatmapLayer({
    data: data,
    map: map
  });

}

如果您遵循 Google 示例,您需要将脚本请求中的回调参数从 callback=initMap 更改为 callback=requestPoints

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    相关资源
    最近更新 更多