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

此外,json_encode 与 2 个在线用户返回的内容:

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

2 回答 2

2

您还应该将地图对象分配给标记(假设您的地图对象名为 map )

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

  };
}
于 2018-03-25T09:39:29.963 回答
1

为了帮助您识别问题,查看javascript地图 api 的其余代码以及运行后有多个用户时的数组会很有用json_encode()。也就是说,请尝试以下操作:

const results = <? php echo json_encode($resulting); ?>;

for(let i = 0; i < results.length; i++) {
  let marker = new google.maps.Marker({
    position: {lat: results[1], lng: results[2]},
    content: '<h1>' + results[0] + </h1>,
    map: map
  });
}

编辑:

我没有在我测试你的代码的目录中安装 Composer,而且我对 Google 实时 API 的工作不多,但是javascript考虑到你列出的输出,以下内容将起作用$resulting。您必须根据自定义图标的来源进行调整,但这应该非常简单。

<!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 $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>

<script>
  const resultingArr = <?php echo json_encode($resulting); ?>;

  function initMap() {
    var options = {
      zoom: 7,
      center: {
        lat: 52.0907,
        lng: 5.1214
      }
    }

    var map = new google.maps.Map(document.getElementById('map'), options);

    function mapMarkers(props) {
      const marker = new google.maps.Marker({
        position: props.coords,
        map: map,
        icon: props.iconImage
      });

      const infoWindow = new google.maps.InfoWindow({
        content: props.content
      });

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

      marker.addListener('mouseout', function() {
        infoWindow.close();
      });
    }

    for (let i = 0; i < resultingArr.length; i++) {
      mapMarkers({
        coords: {
          lat: parseFloat(resultingArr[i][2]),
          lng: parseFloat(resultingArr[i][1])
        },
        content: '<h3>' + resultingArr[i][0] + '</h3>'
      })
    }
  };

</script>
<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>

希望这可以帮助!

于 2018-03-25T10:42:38.267 回答