javascript - 使用 json_encode 从 php 到 javascript 的数据传输

标签 javascript php json google-maps

我正在构建一个 Google map 页面,该页面使用经纬度数据坐标来创建热图,以显示某个区域中狐狸的繁殖情况。

就目前而言,当经纬度值像这样硬编码到我的 index.php 上的 JavaScript 函数 get_points 中时,我的应用程序可以正常工作。

index.php (NB: This code works if tested but requires a google maps api key to load map and heatmap points)

<?php require_once("resources/config.php"); ?>

<!DOCTYPE html>
<html>
 <head>
   <title>Heatmaps</title>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
   <meta charset="utf-8">
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
   <link rel="stylesheet" href="css/style.css">
   <style>
     /* NOTE - GOOGLE MAPS NEED HTTPS (SECURE ORIGIN) OR IT WILL NOT SHOW A MAP. IT WILL CATEGORICALLY NOT WORK ON HTTP*/
     #map {
       /*height: 425px;*/
       height: 100%; 
     }
     /* Optional: Makes the sample page fill the window. */
     html, body {
       height: 100%;
       margin: 0;
       padding: 0;
     }
     #floating-panel {
       position: absolute;
       bottom: 10px;
       /*left: 25%;*/
       z-index: 5;
       background-color: #fff;
       padding: 5px;
       border: 1px solid #999;
       text-align: center;
       font-family: 'Roboto','sans-serif';
       line-height: 30px;
       padding-left: 10px;
     }
     #floating-panel {
       background-color: #fff;
       border: 1px solid #999;
       /*left: 25%;*/
       left: 6%;
       padding: 5px;
       position: absolute;
       /*top: 10px;*/
       z-index: 5;
     }
   </style>
 </head>
 <body>
<!--NOTE - GOOGLE MAPS NEED HTTPS (SECURE ORIGIN) OR IT WILL NOT SHOW A MAP. -->
   <div id="floating-panel">
     <button onclick="changeRadius()">Danger Radius</button>
   </div>
   <div id="map">
    <!--Google map is renderedhere-->
   </div>
   <script>
     function showPosition(){
         if(navigator.geolocation){
             navigator.geolocation.getCurrentPosition(initMap, showError);
         } else{
             alert("Sorry, your browser does not support HTML5 geolocation.");
         }
     }

     var map, heatmap;

     function initMap(position) {
       lat = position.coords.latitude;
       long = position.coords.longitude;

       var latlong = new google.maps.LatLng(lat, long); 
       var myOptions = {
           center: latlong,
           zoom: 16,
           mapTypeControl: true,
           navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
       }

       var map = new google.maps.Map(document.getElementById("map"), myOptions);

       var marker = new google.maps.Marker({position:latlong, map:map, title:"You are here!"});
       heatmap = new google.maps.visualization.HeatmapLayer({
         data: getPoints(), //
         map: map
       });
     }

     // Define callback function for failed attempt
           function showError(error){
               if(error.code == 1){
                   result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
               } else if(error.code == 2){
                   result.innerHTML = "The network is down or the positioning service can't be reached.";
               } else if(error.code == 3){
                   result.innerHTML = "The attempt timed out before it could get the location data.";
               } else{
                   result.innerHTML = "Geolocation failed due to unknown error.";
               }
           }

     function changeGradient() {
       var gradient = [
         'rgba(0, 255, 255, 0)',
         'rgba(0, 255, 255, 1)',
         'rgba(0, 191, 255, 1)',
         'rgba(0, 127, 255, 1)',
         'rgba(0, 63, 255, 1)',
         'rgba(0, 0, 255, 1)',
         'rgba(0, 0, 223, 1)',
         'rgba(0, 0, 191, 1)',
         'rgba(0, 0, 159, 1)',
         'rgba(0, 0, 127, 1)',
         'rgba(63, 0, 91, 1)',
         'rgba(127, 0, 63, 1)',
         'rgba(191, 0, 31, 1)',
         'rgba(255, 0, 0, 1)'
       ]
       heatmap.set('gradient', heatmap.get('gradient') ? null : gradient);
     }

     function changeRadius() {
       heatmap.set('radius', heatmap.get('radius') ? null : 20);
     }

     function changeOpacity() {
       heatmap.set('opacity', heatmap.get('opacity') ? null : 0.4);
     }

     function getPoints() {
       return [
         //////////////////// I DONT WANT TO HAVE TO HARD CODE THESE VALUES ///////////////////////////////////////////

         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 
         new google.maps.LatLng(55.922179, -4.415), 

         // ///////////////////////////////////////////////////////////////

         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256), 
         new google.maps.LatLng(55.910083, -4.403256),
         new google.maps.LatLng(55.910083, -4.403256),
         new google.maps.LatLng(55.910083, -4.403256),

         // ///////////////////////////////////////////////////////////////

         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         new google.maps.LatLng(55.91088, -4.40407), 
         ///////////////////////////////////////////////////////////////////////////

         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 
         new google.maps.LatLng(55.91067, -4.403390), 

         // /////////////////////////////////////////////////////////////////////////

         new google.maps.LatLng(55.91055, -4.404099),
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099), 
         new google.maps.LatLng(55.91055, -4.404099),
         new google.maps.LatLng(55.91055, -4.404099), 
 // ////////////////////////////////////////////////////////////////////////////
         new google.maps.LatLng(55.91067, -4.403648),
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
         new google.maps.LatLng(55.91067, -4.403648), 
        ////////////////////////////////////////////////////////////////////////////////////
       ];
     }
   </script>

   <script async defer
       src="https://maps.googleapis.com/maps/api/js?key=APIKEY=visualization&callback=showPosition">
   </script>

   <!--javascript and jquery CDN's directly beneath here-->
   <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
   <script  src="js/index.js"></script>
 </body>
</html>

问题是,我不想在我的 get_points() 函数中对经纬度坐标进行硬编码。

我无法使用我设计的使用 json_encode 的 php 函数将这些经纬度点从我的 MySQL 表提供给上述函数。

我收到的错误主要是“不是有效的 MVC 数组”。但奇怪的是,我可以打印出数组。

My Table Schema

db table

My Custom PHP function

function get_coordinates() {
        $coordinates = array(); // initial decleration of memory 
        $latitudes = array(); // see above
        $longitudes = array(); // see above

        // Select all the rows in the location_values table
        $hotpointquery = query("SELECT `locationLatitude`, `locationLongitude` FROM `location_values` ");
        confirm($hotpointquery);

        while ($row = fetch_array($hotpointquery)) {
            $latitudes[] = $row['locationLatitude'];
            $longitudes[] = $row['locationLongitude'];

            // instantiate new map php array which is a COMBINATION of $latitudes and $longitudes and google map object. 
            $coordinates[] = 'new google.maps.LatLng(' . $row['locationLatitude'] .','. $row['locationLongitude'] .'),';  

            //convert the PHP array into JSON format, so it works with javascript
            $json_array = json_encode($coordinates);
        }

        //this block removes comma in very last lat lang element in our db
        $lastcount = count($coordinates)-1; // dorman : counts all lat lang in the databse n-1;
        $coordinates[$lastcount] = trim($coordinates[$lastcount], ",");  // for each pair, use trim function to remove the white space and comma in the last element of our lat lang at end of db

        // echo print_r($coordinates[$lastcount]); // this only prints out one set of lat langs
} // end of function/////////////

new_get_points()

function getPoints() {
  var array = <?php echo $json_array;?>
}

最佳答案

JSON 是一种数据交换格式,而不是一种编程语言。当您在字符串中包含诸如“new google.maps.LatLng...”之类的内容时,就是这样:一个字符串。它没有任何意义——即使它有意义,您的 PHP 代码也不会返回任何东西,您的 JavaScript 代码也不会执行任何东西。

虽然您的方向是对的,所以让我们做一些小的改变。

在您的 PHP 中,您可以这样做:

<?php

function get_coordinates() {
    $hotpointquery = query("SELECT `locationLatitude`, `locationLongitude` FROM `location_values` ");
    confirm($hotpointquery);
    while ($row = fetch_array($hotpointquery)) {
        $coordinates = [$row['locationLatitude'], $row['locationLongitude']];
    }
    return json_encode($coordinates);
}

在页面的后面,在 <script> 内元素,你可以让 PHP 打印出那个数组,然后 JS 可以使用 map 将它操作成你正在寻找的对象。功能:

function getPoints() {
   var coords = <?= get_coordinates() ?>
   var points = coords.map(function(coord) {
       return new google.maps.LatLng(coord[0], coord[1]);
    });
    return points;
}

关于javascript - 使用 json_encode 从 php 到 javascript 的数据传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544687/

相关文章:

javascript - 给定 JSON 中的第一行是什么?

.net - jqGrid - 如何配置 jsonreader(与 Jayrock 一起使用)?

javascript - 整数被计算为数字但输出不是数字(NaN)?

javascript - 使用 jQuery 从 URL 获取最后一个字符串

php - 如何替换由 mysql 和 php 生成的 json 字符串中的回车?

php - 使用 Codeigniter 在数据库中搜索确切的单词

javascript - 如何为 Bootstrap slider 添加 onclick 功能?

javascript - 为什么 postMessage 脚本在 IE8 中不起作用?

php - 使用模板的电子邮件功能。通过 ob_start 和全局变量包含

javascript - 从 php json 解码中检索 json 数组