似乎无法在 Google 地图上获得标记点击来执行任何操作

Cannot seem to get marker clicks on Google Maps to do anything

我有一个简单的 Google 地图专长,我正在尝试但未能完成。

目前,我可以显示我的地图,然后通过 PHP(我正在使用 ExpressionEngine)循环浏览项目列表,并将每个项目的 latitude/longitude 添加到 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>

您正在尝试在 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 );
     });

  });