如何正确地将php数组传递给leatlef heatmap?

brc7rcf0  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(459)

我对php和mysql还不熟悉,所以这个任务让我很费劲:我有一个mysql数据库,里面有很多地理坐标,需要用php提取出来,转换成json格式传递给javascript,然后显示在传单的热图上。
我已经编写了js代码,ajax似乎可以正常工作了。但热图似乎不接受我的包含坐标的数组。我看不出我在哪里犯了错;我认为我的php数组的格式不正确。
热图需要以以下格式获取其数据:

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

那么,如何让这个数组看起来像热图需要的那个?
编辑:
所以我把我的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
)

//等等
@你是那个意思吗?

6jjcrrmo

6jjcrrmo1#

我在你的代码里看到的第一件事就是 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);
....

相关问题