google 用实时数据绘制 api 个标记

google map api markers with realtime data

我目前有实时分析 php api。它有一个名为 $resulting 的实体。如果我这样做 print_r($resulting);例如 returns(如果只有 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>

另外,json_encodereturns有2个用户在线:

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

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

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

  };
}

为了帮助您确定问题,查看地图 api 的其余 javascript 代码以及 api 之后有多个用户时的数组会很有用=29=] 它虽然 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>

希望对您有所帮助!