简体   繁体   English

由 JavaScript 为 Google Maps Legend 创建的 html 元素的事件侦听器不起作用

[英]Event listeners to html elements created by javascript for Google Maps Legend is not working

I'm trying to use Javascript to add event listeners to several links that are created via Javascript.我正在尝试使用 Javascript 将事件侦听器添加到通过 Javascript 创建的多个链接。 I thought that I am probably calling it before it is created but looked at some other examples (such as add event listener on elements created dynamically and Google Map Event Listener does not seem to work ) on here and thought that if those work I should probably be fine as well.我想我可能会在它被创建之前调用它,但在此处查看了一些其他示例(例如在动态创建的元素上添加事件侦听器,Google Map Event Listener 似乎不起作用),并认为如果这些工作我可能应该也很好。 If anyone could point out where I'm going wrong it would be greatly appreciated.如果有人能指出我哪里出错了,将不胜感激。

*It seems like it would be way easier for everyone to just put the whole snippet in. *似乎每个人都将整个代码段放入会更容易。

Also as of right now I'm getting "P1 [object HTMLParagraphElement]" for when I console.log("P1 " + precinct1同样截至目前,当我console.log("P1 " + precinct1

JS Snippet: 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);

I don't know much about google maps api, but the code seems a bit weird to me.我对 google maps api 了解不多,但代码对我来说似乎有点奇怪。 You add plain HTML text as strings into an array which aren't placed in the dom/your div.您将纯 HTML 文本作为字符串添加到未放置在 dom/您的 div 中的数组中。 Even the document.getElementById('precinct1');甚至document.getElementById('precinct1'); should not work.不应该工作。

You have to append your links into the dom/your div first, after that register the event handler for each item:您必须首先将链接附加到 dom/您的 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");
    });
}

If i'm wrong: Feel free to blame me.如果我错了:请随意责怪我。

The problem is that (as you point it out) you are using it before it is created.问题是(正如您指出的那样)您在创建它之前正在使用它。 Options:选项:

  1. Create it (and actually add it to the document), then cache it, then call it.创建它(并实际将其添加到文档中),然后缓存它,然后调用它。
  2. Do not cache it (advise against this)不要缓存它(建议不要这样做)
  3. Delegate from the container they are added in (preferred)从添加它们的容器中委托(首选)

I have not used the Google Maps API, but something like this might work (assuming it captures the same mouse event:我没有使用过 Google Maps API,但是这样的东西可能会起作用(假设它捕获相同的鼠标事件:

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

Where precinctContainer is the container you put all those <a> tags in the content array.其中precinctContainer是您将所有那些<a>标签放入content数组中的容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM