1

私は現在、リアルタイム分析php APIを持っています。という名前のこのエンティティがあり$resultingます。もしそうならprint_r($resulting); たとえば、次のように返されます (オンラインのユーザーが 1 人だけの場合):

Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )

さて、後で同じファイルに、Google マップの JavaScript API があります。次の形式のマーカーがあります。

var markers = [
            {
                coords:{lat:52.0907,lng:5.1214},
                content:'<h1>Utrecht</h1>'
            },
            {
                coords:{lat:52.0907,lng:5},
                content:'<h1>Links</h1>'
            },
            {
                coords:{lat:52.0907,lng:6},
                content:'<h1>Rechts</h1>'
            }
         ]; 

今のところプレースホルダーとして。私がやりたいことは、coords:セクションにlat:lng:からの適切な値を持たせることです$resulting。また、オンラインのユーザーと同じ数のマーカーが必要です。

今、考えられることはすべて試しましたが、うまくいきません。私は例えば試してみました:

const results = <? php echo json_encode($resulting); ?>;
let markers = [];

for(let i = 0; i < results.length; i++) {
    markers[i] = {
        coords: {
            lat: results[1],
            lng: results[2]
        }
    };
}

しかし、その後、マップはもう読み込まれません。foreach をループして、lat: と lng: を取得して $resulting によって返された値で更新しようとしましたが、何をしてもうまくいきません。

誰でも私を助けて、これを機能させることができますか?

ありがとう。

編集: 要求に応じて index.php ファイルを追加:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="jquery.json-2.4.min.js"></script>
    <title>My Google Map</title>
    <style>
        #map{
            height: 400px;
            width:400px;
        }
    </style>
</head>
<body>
    <h1>My Google Map</h1>
    <div id="map"></div>

<?php
require_once  __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_Analytics($client);

  return $analytics;
}
/**
 * 1.Create and Execute a Real Time Report
 * An application can request real-time data by calling the get method on the Analytics service object.
 * The method requires an ids parameter which specifies from which view (profile) to retrieve data.
 * For example, the following code requests real-time data for view (profile) ID 56789.
 */
$optParams = array(
    'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');

try {
  $resultsrealtime = $analytics->data_realtime->get(
      'ga:MY GOOGLE CLIENT ID',
      'rt:activeUsers',
      $optParams);
  // Success.
} catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e->getMessage();
}


/**
 * 2. Print out the Real-Time Data
 * The components of the report can be printed out as follows:
 */
$resulting = $resultsrealtime->getRows();
function test() {
  if(count($resulting == false)){
  return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
  foreach ($resultingThree as $resultingFour){
      echo $resultingFour.'<br />';
  }
}
} else {
    echo 'No visitors';
}
}
?>
<script>
    // Map options
    function initMap(){
        var options = {
            zoom:7,
            center:{lat:52.0907, lng:5.1214}
        }
        // New map
        var map = new google.maps.Map(document.getElementById('map'), options);


        // Array of markers
        var markers = [
            {
                coords:{lat:52.0907,lng:5.1214},
                iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
                content:'<h1>Utrecht</h1>'
            },
            {
                coords:{lat:52.0907,lng:5},
                content:'<h1>Links</h1>'
            },
            {
                coords:{lat:52.0907,lng:6},
                content:'<h1>Rechts</h1>'
            }
         ]; 

         // Loop through markers
         for(var i = 0; i < markers.length; i++){
             // add Marker
            addMarker(markers[i]);
         }

        // Add Marker Function
        function addMarker(props){
            var marker = new google.maps.Marker({
                position: props.coords,
                map:map,
                //icon:props.iconImage
            });

            // Check for custom icon
            if(props.iconImage){
                // Set icon image
                marker.setIcon(props.iconImage);
            }

            // Check for content
            if(props.content){
                // Set content
                // Info Window
        var infoWindow = new google.maps.InfoWindow({
            content:props.content
        });

        marker.addListener('mouseover', function(){
            infoWindow.open(map, marker);

        // Reset Info Window
            setTimeout(function(){
                infoWindow.open()
            }, 500);
         }, false);
            }
        }

    }
</script>
    <div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>

また、2 人のユーザーがオンラインで json_encode が返すもの:

[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
4

2 に答える 2