我使用Google Maps Javascript API创建了一个包含地图的网站。我使用PHP从Google BigQuery数据库中调用$ rows。我想为地图上的所有标记添加一个监听器。目前,点击的任何标记都会跳转到最终标记,就像它将所有剩余标记循环到最终标记一样。
foreach ($rows as $row) {
?>
var contentString = "<h1><?php echo str_replace('"', "'", $row['f'][2]['v']); ?></h1>";
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var geolocate = new google.maps.LatLng(<?php echo $row['f'][0]['v']; ?> , <?php echo $row['f'][1]['v']; ?>);
var marker = new google.maps.Marker({
map: map,
position: geolocate,
icon: '/img/Toilet.png',
title: "<?php echo str_replace('"', "'", $row['f'][2]['v']); ?>" //String Replace
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
我想象一下marker.addListener需要一个指向数组索引的指针,但我不能解决它,我该怎么办?
答案 0 :(得分:1)
您可以使用IIFE模式。请看看
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
在这种情况下,您的代码将类似于:
<?php
foreach ($rows as $row) {
?>
(function() {
var contentString = "<h1><?php echo str_replace('"', "'", $row['f'][2]['v']); ?></h1>";
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var geolocate = new google.maps.LatLng(<?php echo $row['f'][0]['v']; ?> , <?php echo $row['f'][1]['v']; ?>);
var marker = new google.maps.Marker({
map: map,
position: geolocate,
icon: '/img/Toilet.png',
title: "<?php echo str_replace('"', "'", $row['f'][2]['v']); ?>" //String Replace
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
})();
<?php
}
?>