谷歌地图api标记与实时数据(google map api markers with realtime data)

编程入门 行业动态 更新时间:2024-10-26 02:29:40
谷歌地图api标记与实时数据(google map api markers with realtime data)

我目前有实时分析php api。 它有一个名为$resulting实体。 如果我做print_r($resulting) ; 它返回例如(如果只有一个用户在线):

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

现在,稍后在同一个文件中,我有谷歌地图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: section有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:使用$ result返回的值进行更新,但无论我做什么,它都无法正常工作。

任何人都可以帮助我并让它工作吗?

谢谢。

编辑:按要求添加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"]]

I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):

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

Now, later on in the same file, I have the google maps javascript api. It has markers in the form of:

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

As placeholder for now. What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting. Also, I want to have as many markers as there are users online.

Now, I have tried everything I can think of, but I can't get it to work. I have tried for example:

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

but then the maps won't load anymore. I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.

Can anybody help me and get this working?

Thanks.

edit: adding the index.php file as requested:

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

Also, what the json_encode returns with 2 users online:

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

最满意答案

为了帮助您识别问题,查看地图api的其余javascript代码以及在通过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>

希望这可以帮助!

To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:

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

Edit:

I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.

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

Hope this helps!

更多推荐

本文发布于:2023-08-07 13:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实时   标记   地图   数据   realtime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!