自定义Google地图以打开标记链接

时间:2014-11-13 13:58:06

标签: javascript wordpress google-maps google-maps-api-3 wordpress-theming

我正在开发一个项目,Google Maps标记会在点击时打开链接。问题是数组中的最后一个条目打开而不是前面的条目。我只是看不出问题。它填充在Wordpress的模板页面上,我在functions.php文件中使用了wp_enqueue_script。 header.php文件包含Google Maps API密钥。任何帮助将不胜感激。谢谢。

function initialize() {
    var mapOptions = {
      center: { lat: 32.5851061, lng: -89.8772196},
      zoom: 8
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
    setMarkers(map, communities);
  }
  var communities = [
  ['Oxford', 34.360004, -89.5233875, 'http://oxfordcycling.org'],
  ['Starkville', 33.4562909, -88.8322225, 'http://starkvillecyclingclub.org'],
  ['Natchez', 31.544537, -91.3862539,     'http://crookedlettercycling.com/communities/natchez'],
  ['Ridgeland', 32.42941, -90.1454013, 'http://ridgelandms.com']
  ];
  function setMarkers(map, locations) {
    for (var i = 0; i < locations.length; i++) {
      var community = locations[i];
      var myLatLng = new google.maps.LatLng(community[1], community[2]);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: community[0],
        url: community[3],
      });
    }
    google.maps.event.addListener(marker, 'click', function() {
        window.open(this.url, '_blank');
    });
  }
  google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

事件监听器应位于for循环内,否则只有最后一个标记将接收单击事件。

for (var i = 0; i < locations.length; i++) {
      var community = locations[i];
      var myLatLng = new google.maps.LatLng(community[1], community[2]);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: community[0],
        url: community[3],
      });
     google.maps.event.addListener(marker, 'click', function() {
        window.open(this.url, '_blank');
    });
}