如何正确地将PHP数组传递给Leatlef Heatmap?

时间:2018-01-13 11:01:09

标签: javascript php mysql leaflet heatmap

我是PHP和MySQL的新手,所以这项任务真让我苦苦挣扎: 我有一个MySQL数据库,其中包含许多地理坐标,这些坐标应由php提取,转换为JSON格式以将其传递给JavaScript,然后显示在Leaflet的热图中。

我已经编写了JS代码,而AJAX似乎正在运行。但是Heatmap似乎并不接受包含坐标的数组。我看不出我弄错了什么;我认为我的PHP数组没有以正确的方式格式化。

Heatmap需要以这种格式获取数据:

var testData = {
  max: 8,
  data: [{lat: 24.6408, lng:46.7728, count: 1},{lat: 50.75, lng:-1.55, count: 1}, ...]
};

这是我现在的代码:

var geoData;

function loadData() {
  alert("loading Data");
  getJSON();
}

function getJSON() {
  $.ajax({
    url: "assets/php/readGeoData.php",
    type: "GET",
    datatype: "json",
    success: function(data) {
      alert("ajax transfer successful ");
      geoData = data;
      //For debugging:
      alert(getGeoData());
    }
  })
}

function getGeoData() {
  return geoData;
}
<!DOCTYPE html>
<html lang="de">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->

  <!-- Leaflet CSS -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin="" />
  <!-- Leaflet JS -->
  <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
  <!-- Leaflet Heatmap JS -->
  <script src="assets/js/Leaflet.heat-gh-pages/dist/leaflet-heat.js"></script>
  <!-- map CSS -->
  <link rel="stylesheet" href="assets/css/map.css" />
  <!-- map JS -->
  <script src="assets/js/mymap.js"></script>
  <!-- main CSS -->
  <link rel="stylesheet" href="assets/css/main.css" />
  <!-- jQuery -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- data JS -->
  <script src="assets/js/loadGeoData.js"></script>

</head>

<body>
  <h1>movementprofile</h1>

  <button id="importButton">import geoData</button>
  <div id="mapid"></div>

  <script>
    $("#importButton").click(function() {
      loadData();
    });
  </script>

  <!-- creating the map -->
  <script>
    var mymap = L.map('mapid').setView([51.25, 10.5], 6);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxToken, {
      maxZoom: 18,
      attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
      id: 'mapbox.streets'
    }).addTo(mymap);
  </script>
  <script>
    var heatmapData = {
      max: 8,
      data: getGeoData()
    };

    var heatmapLayer = new HeatmapOverlay(cfg);

    heatmapLayer.setData(8, getGeoData());
  </script>
</body>

</html>

PHP:

<?php

$db = new PDO('mysql:host=127.0.0.1;dbname=movementprofile;', 'root', *****);

$query ='SELECT longitude, latitude FROM movementprofile WHERE longitude IS NOT NULL AND latitude  IS NOT NULL';

foreach ($db->query($query) as $row) {

    print_r($row);

    $longitude = $row['longitude'];
    $latitude = $row['latitude'];

    $singleDataset = array('lon' => $longitude,'lat' => $latitude, 'count'=> 1);
    array_push($datasets,$singleDataset, JSON_FORCE_OBJECT);
    echo json_encode($datasets);
}

这是我现在得到的数组(在JS警告框中):

    Array
(
    [longitude] => 13.39611111
    [0] => 13.39611111
    [latitude] => 52.52944444
    [1] => 52.52944444
)
nullArray
(
    [longitude] => 13.37472222
    [0] => 13.37472222
    [latitude] => 52.53027778
    [1] => 52.53027778
)
nullArray
(
    [longitude] => 13.38361111
    [0] => 13.38361111
    [latitude] => 52.53
    [1] => 52.53
)
//... and so on, there are more than 30.000 entries

那么,我如何让这个数组看起来像Heatmap需要的呢?

编辑:

所以我编辑了我的PHP:

    foreach ($db->query($query) as $row) {
    print_r($row);

    $longitude = $row['longitude'];
    $latitude = $row['latitude'];

    $singleDataset = array('lon' => $longitude,'lat' => $latitude, 'count'=> 1);
    array_push($datasets,json_encode($singleDataset));

但仍然有这个数组:

        Array
(
    [longitude] => 13.39611111
    [0] => 13.39611111
    [latitude] => 52.52944444
    [1] => 52.52944444
)

//等等

@thinsoldier 你的意思是?

1 个答案:

答案 0 :(得分:0)

我在代码中看到的第一件事就是你print_r($row); - 删除或评论。

另外也许可以看看我的php连接器如何创建geojson(例子与postgres连接,但你可以简单地将其重写为mysql并调整到你的数据库结构):

<?php

$dbconn = pg_connect("host=localhost port=5432 dbname=pguser user=pguser password=pass");
$result = pg_query($dbconn, "SELECT * FROM test");

$geojson = array(
   'type'      => 'FeatureCollection',
   'features'  => array()
);

while($row = pg_fetch_assoc($result)) {
    $feature = array(
        'id' => $row['id'],
        'type' => 'Feature', 
        'geometry' => array(
            'type' => 'Point',
            'coordinates' => array($row['latitude'], $row['longitude'])
        ),
        # Pass other attribute columns here
        'properties' => array(
            'test' => 'test',
            'column1' => $row['column1'],
            'column2' => $row['column2']
            )
        );
    # Add feature arrays to feature collection array
    array_push($geojson['features'], $feature);
}

header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);

?>

修改

因为你想获得json的特定结构,而不是具有特性的geoJson,所以上面的代码可以简化为:

....
$json = array(
   'max'      => '8',
   'data'  => array()
);

while($row = pg_fetch_assoc($result)) {
    $data = array(
        'lat' => $row['latitude'],
        'lng' => $row['longitude'],
        'count' => '1', 
        );
    # Add feature arrays to feature collection array
    array_push($json['data'], $data);
}

header('Content-type: application/json');
echo json_encode($json, JSON_NUMERIC_CHECK);
....