通过javascript为Google Maps Legend创建的html元素的事件侦听器无法正常工作

时间:2015-01-12 19:36:54

标签: javascript html javascript-events event-listener

.Hello我正在尝试使用Javascript将事件监听器添加到通过Javascript创建的多个链接中。我认为我可能在它创建之前调用它,但在这里查看了一些其他示例(例如add event listener on elements created dynamicallyGoogle Map Event Listener does not seem to work),并认为如果这些工作我也应该没问题。如果有人能指出我出错的地方,我将不胜感激。

*似乎每个人都可以更轻松地将整个代码段放入其中。

此时我现在正在获取“P1 [object HTMLParagraphElement]”,因为我在console.log(“P1”+ precinct1

再次感谢!

JS片段:

    function initialize() {

  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(123, 123),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

/*
Creating Map - Do not create with Fusion Tables directly so that you have control
of how the polygons are drawn.
*/
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

  //Initialize JSONP request

  var script = document.createElement('script');
  var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
  url.push('sql=');
  var query = 'SELECT COMMISH, geometry, Website FROM ' + tableId;
  var encodedQuery = encodeURIComponent(query);
  url.push(encodedQuery);
  url.push('&callback=drawMap');
  url.push('&key=' + key);
  script.src = url.join('');
  var body = document.getElementsByTagName('body')[0];
  body.appendChild(script);
}

  function createPolygon(precinct, url, comPrecinct){
    google.maps.event.addListener(precinct, 'mouseover', function() {
      this.setOptions(
        {
          fillOpacity: 0.5,
          strokeOpacity: 1,
        }
      );

    });

    google.maps.event.addListener(precinct, 'mouseout', function() {
      this.setOptions(
        {
          fillOpacity: 0.3,
          strokeOpacity: 0,
        }
      );
    });

    google.maps.event.addListener(precinct, 'click', function(){
      window.location = url;
    });

  }

  function drawMap(data) {
        var rows = data['rows'];
        console.log(rows);
        /*Create Legend*/
        var legend = document.createElement('div');
        legend.id = 'legend';
        var content = [];
        content.push('<a href="#"><p class="precinct" id="precinct1"></div>Precinct 1</p></a>');
        content.push('<a href="#"><p class="precinct" id="precinct2"></div>Precinct 2</p></a>');
        content.push('<a href="#"><p class="precinct" id="precinct3"></div>Precinct 3</p></a>');
        content.push('<a href="#"><p class="precinct" id="precinct4"></div>Precinct 4</p></a>');

       legend.innerHTML = content.join('');
       legend.index = 1;
       map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

        for (var i in rows) {
            var comPrecinct = rows[i][0];
            var url = rows[i][2];
            var newCoordinates = [];
            var geometries = rows[i][1]['geometries'];

            if (geometries) {
              for (var j in geometries) {
                newCoordinates.push(constructNewCoordinates(geometries[j]));
              }
            } else {
              newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
            }

            /*
              Colors are out of order because precincts are out of order
              in KML files. Adjust CSS as necessary.
            */
            var precinct = new google.maps.Polygon({
              paths: newCoordinates,
              strokeColor: colors[i],
              strokeOpacity: 0,
              strokeWeight: 1,
              fillColor: colors[i],
              fillOpacity: 0.3,
            });


            createPolygon(precinct, url, comPrecinct);

            precinct.setMap(map);

        }

      console.log('P1 ' + precinct1);
      google.maps.event.addListener(legend, 'hover', function(e){
          if(e.target.id === 'precinct1'){
            console.log("P1 - aawwwww yis");
          }
        });

  }

  function constructNewCoordinates(polygon){
    var newCoordinates = [];
    var coordinates = polygon['coordinates'][0];
    for (var i in coordinates){
      newCoordinates.push(new google.maps.LatLng(coordinates[i][1], coordinates[i][0]));
    }
    return newCoordinates;
  }

google.maps.event.addDomListener(window, 'load', initialize);

P].push(legend);

2 个答案:

答案 0 :(得分:1)

我对google maps api了解不多,但代码对我来说似乎有些奇怪。您将纯HTML文本作为字符串添加到数组中,这些数组未放在dom / div中。即使document.getElementById('precinct1');也不行。

您必须首先将链接附加到dom / your div中,然后注册每个项目的事件处理程序:

legend.innerHTML += content.join('');

var links = legend.getElementsByTagName('p'); // these are your items with the id you want to bind

for(var i = 0; i < links.length; i++) {
    google.maps.event.addListener(links[i], 'hover', function(){
        console.log("Aww yis");
    });
}

如果我错了:请随意责备我。

答案 1 :(得分:1)

问题在于(当你指出它时)你在创建之前就使用它了。选项:

  1. 创建它(实际上将其添加到文档中),然后缓存它,然后调用它。
  2. 不要缓存它(建议不要这样做)
  3. 从容器中委派他们(首选)
  4. 我没有使用过谷歌地图API,但这样的事情可能有用(假设它捕获相同的鼠标事件:

    google.maps.event.addListener(precinctContainer, 'hover', function(e){
        if(e.target.id === 'precinct1'){
            console.log("Aww yis");
        }
    });
    

    precinctContainer是容器的位置,您将所有<a>标记放在content数组中。