用PHP值填充JavaScript变量

时间:2019-03-06 09:02:06

标签: javascript php

此map.php页面显示一个包含mongoDB文档的表,其中包含用于坐标读取的时间,纬度和经度。

它还使用google API在地图上显示位置(硬连线)。我想将Google地图脚本读取的经度/纬度替换为具有最大“时间”值(又称最新项)的表项的纬度/经度。我知道您可以直接将php echo语句编写为获取值,但是如您所见,我有一个循环来获取表条目,在这里做我想做的事是否现实? PHP学习者,绝对mongodb和javascript新手在这里。感谢您的帮助!

编辑:已解决,已根据选定答案编辑为有效的解决方案。谢谢大家。

   <!DOCTYPE html>
<html>
  <head>
    <style>
       /* Set the size of the div element that contains the map */
      #map {
        height: 400px;  /* The height is 400 pixels */
        width: 100%;  /* The width is the width of the web page */
       }
    </style>
  </head>
  <body>
    <h3>Last Locations</h3>

    <?php
    //name of DB: muntean Name of collection:TestData
    $user = "muntean";
    require '/var/composer/vendor/autoload.php';
    $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $collection = new MongoDB\Collection($manager, $user, 'testData');

    $data  = "<table style='border:1px solid red;";
    $data .= "border-collapse:collapse' border='1px'>";
    $data .= "<thead>";
    $data .= "<tr>";
    $data .= "<th>Time</th>";
    $data .= "<th>Longitude</th>";
    $data .= "<th>Latitude</th>";
    $data .= "</tr>";
    $data .= "</thead>";
    $data .= "<tbody>";

   try{
    $cursor = $collection->find();
    $largest =  0;
   foreach($cursor as $document){
   if ($largest < $document["Time"]) {
       $largest = $document["Time"];
       $longitude = $document["Longitude"];
       $latitude = $document["Latitude"];
   }

   $data .= "<tr>";
   $data .= "<td>" . $document["Time"] . "</td>";
   $data .= "<td>" . $document["Longitude"]."</td>";
   $data .= "<td>" . $document["Latitude"]."</td>";
   $data .= "</tr>";
  }
  $data .= "</tbody>";
  $data .= "</table>";
  echo $data;
  }catch(MongoException $mongoException){
    print $mongoException;
    exit;
}


     ?>

    <!--The div element for the map -->
    <div id="map"></div>
    <script>
// Initialize and add the map
function initMap() {
  // The location of point
   var point = {lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>}
  // The map, centered at point
  var map = new google.maps.Map(
      document.getElementById('map'), {zoom: 12, center: point});
  // The marker, positioned at point
  var marker = new google.maps.Marker({position: point, map: map});
}
    </script>
    <!--Load the API from the specified URL
    * The async attribute allows the browser to render the page while the API loads
    * The key parameter will contain your own API key (which is not needed for this tutorial)
    * The callback parameter executes the initMap() function
    -->
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6CMFIF-m8Z_kNLUGT7HEVBew_wPLno7o&callback=initMap">
    </script>

  </body>
</html>

位置随机What it looks like, map should be centered on the table datta though

3 个答案:

答案 0 :(得分:2)

您只需要在PHP的Json中编码变量即可使用JS获得字符串。然后您解码Json,并将您的变量放入一个漂亮的JS对象中

<script>
let json= "<?php echo json_encode($variables); ?>";
let obj = JSON.parse(json);
</script>

答案 1 :(得分:1)

在PHP循环中,您可以保存具有最大时间值的经度和纬度,例如:

$largest =  0;
foreach($cursor as $document){
   if ($largest < $document["Time"]) {
       $largest = $document["Time"];
       $longitude = $document["Longitude"];
       $latitude = $document["Latitude"];
   }

   $data .= "<tr>";
   $data .= "<td>" . $document["Time"] . "</td>";
   $data .= "<td>" . $document["Longitude"]."</td>";
   $data .= "<td>" . $document["Latitude"]."</td>";
   data .= "</tr>";
}

在您可以将$longitude$latitude回显到JavaScript中之后

var point = {lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>}

答案 2 :(得分:1)

这里有两个步骤:

  • 获取包含最新数据的文档
  • 将值插入您的JS

对于第一个,如果性能是一个问题(数千个时间范围),则可以利用已经存在的循环,但是对于更简洁的代码,我建议在PHP中声明一个专用函数:

/**
 * Returns the latest data in a collection, or false if none exists
 */
function getLatestData($collection) {
  $cursor = $collection->find();
  $result = null;
  foreach ($cursor as $document) {
    // If it's the first iteration or if this doc is newer
    if ($result === null || $document['Time'] > $result['Time']) {
      $result = $document;
    }
  }
  if ($result !== null) {
    return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];
  }
  return false;
}

然后,在JS内,您可以使用json_encode将结果转换为JSON字符串:

var point = <?=json_encode(getLatestData($collection))?>;