0

我有一个简单的Google地图专长,我正在尝试并未能完成。似乎无法在Google地图上获得标记点击次数

目前,我可以显示我的地图,然后通过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> 

回答

1

正试图在那里被定义的,而不是在循环的循环后添加事件侦听标志​​

尝试:

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

    }); 
+0

谢谢charlietfl! 我不得不作出一个更正:我将marker.title更改为this.title。以前,marker.title返回“This marker的url_title是:undefined”,但现在它返回了预期的数据。 非常感谢您的帮助!你只是让我的一周! – Chris

+0

我没有看文档,我认为回调的第一个参数是标记...我的坏 – charlietfl