簡體   English   中英

使用json_encode將數據從php傳輸到javascript

[英]data transfer from php to javascript using json_encode

我正在構建一個Google地圖頁面,該頁面使用較長的數據坐標來創建熱圖,以顯示區域中狐狸的擴散。

按照目前的情況,當將long值硬編碼到index.php上的JavaScript函數get_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>

問題是,我不想在get_points()函數中對長坐標進行硬編碼。

我很麻煩使用我設計的使用json_encode的php函數從MySQL表向這些函數提供這些較長的點。

我收到錯誤,主要是說“不是有效的MVC數組”。 但是奇怪的是,我可以將陣列打印出來。

我的表架構

db表

我的自定義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()

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM