简体   繁体   English

使用json_encode将数据从php传输到javascript

[英]data transfer from php to javascript using json_encode

I am building a Google maps page that uses lat long data coordinates to create a heat map to show the proliferation of foxes in an area. 我正在构建一个Google地图页面,该页面使用较长的数据坐标来创建热图,以显示区域中狐狸的扩散。

As it currently stands, my app works fine when the lat long values are hard coded into my JavaScript function get_points on my index.php like this. 按照目前的情况,当将long值硬编码到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) index.php(注意:如果经过测试,此代码有效,但需要使用Google Maps API密钥来加载地图和热图点)

<?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>

The problem is, I don't want to hardcode the lat long coordinates in my get_points() function. 问题是,我不想在get_points()函数中对长坐标进行硬编码。

I am having bother serving these lat long points from my MySQL table to the said function using a php function I designed which uses json_encode. 我很麻烦使用我设计的使用json_encode的php函数从MySQL表向这些函数提供这些较长的点。

I am getting errors mainly saying "not a valid MVC array". 我收到错误,主要是说“不是有效的MVC数组”。 Yet strangely, I can print the array out. 但是奇怪的是,我可以将阵列打印出来。

My Table Schema 我的表架构

db table db表

My Custom PHP function 我的自定义PHP函数

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() new_get_points()

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

JSON is a data exchange format , not a programming language. JSON是一种数据交换格式 ,而不是一种编程语言。 When you include something like "new google.maps.LatLng..." in a string, that's all it is: a string. 当您在字符串中包含“ new google.maps.LatLng ...”之类的内容时,仅此而已:字符串。 It doesn't mean anything – and even if it did, your PHP code isn't returning anything, and your JavaScript code isn't executing anything. 这并不意味着任何事情,即使这样,您的PHP代码也不会返回任何内容,而您的JavaScript代码也不会执行任何操作。

You are sort of on the right track though, so let's make some small changes. 不过,您处在正确的轨道上,因此让我们进行一些小的更改。

In your PHP, you can do this: 在您的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);
}

Later in the page, within the <script> element you can have PHP print out that array, then JS can manipulate it into the objects you're looking for using the map function: 在页面的后面,您可以在<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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM