我有一个简单的谷歌地图专长我正在努力并且未能完成。
目前,我可以显示我的地图,然后通过PHP循环浏览项目列表(我正在使用ExpressionEngine),并将每个项目的纬度/经度添加到JavaScript数组中。
一旦值在JavaScript数组中,我使用jQuery循环遍历每个值,并向地图添加标记。
我可以点击地图并让它做出适当的回应;但是,当我试图点击其中一个标记时,根本没有任何事情发生。
我已经尝试过无休止地移动代码,重命名,更改,编辑和调整......我无法理解这一点。任何帮助都将非常感激。我的代码如下:
<script>
// Create the new map_locations array
var map_locations = [];
</script>
<!-- The following ExpressionEngine script loops through all the 'projects' on the site,
then pushes each project to the map_locations array. -->
{exp:channel:entries channel="projects"}
<script>
map_locations.push( ['{url_title}', '{project_latitude}', '{project_longitude}', '{categories}{category_name}{/categories}', '{title}'] );
</script>
{/exp:channel:entries}
<script>
var marker;
function initialize() {
// To add the marker to the map, use the 'map' property
var mapOptions = {
center: { lat: 51.884 , lng: -95.147 },
zoom: 4
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a new location lat/long var, newLatLng
var newLatLng;
var contentString = "<div id='info_window'>this is the info window</div>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var iconBase = '/images/map_icon_';
$.each( map_locations, function()
{
newLatLng = new google.maps.LatLng( this[1] , this[2] );
marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
});
google.maps.event.addListener(marker, 'click', function() {
console.log( "This marker's url_title is: " + this[0] );
});
google.maps.event.addListener(map, 'click', function() {
console.log( "Testing map click" );
});
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
答案 0 :(得分:1)
您试图在定义marker
的循环之后为循环添加事件侦听器而不是在循环中
尝试:
$.each( map_locations, function(){
var newLatLng = new google.maps.LatLng( this[1] , this[2] );
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
google.maps.event.addListener(marker, 'click', function(marker) {
console.log( "This marker's url_title is: " + marker.title );
});
});