Google Maps API - Event Listener for InfoBubble doesn't work

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 13:42:25

问题


I need an event listener waiting for a click. Unfortunately the way it worked with InfoWindows doesn't seem to work here...

Well, here's my InfoBubble:

var infoBubble = new InfoBubble({
      map: map,
      content: $('#my-div').html(),
      position: new google.maps.LatLng(areas[area].lat, areas[area].lng),
      shadowStyle: 1,
      padding: 0,
      borderRadius: 0,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#ccc',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 15,
      arrowStyle: 0
    });

And here's my listener:

google.maps.event.addListener(infoBubble, 'click', function(){

        console.log("noodle");  
    });

BTW, there are no errors reported by Firebug.


回答1:


Try this:

$(infoBubble.bubble_).live("click", function() {
    console.log('clicked!');
});



回答2:


If you're using the compiled version of InfoBubble, the .bubble_ reference is lost. You have to find what .bubble_ has been changed into. If you haven't compiled your own and you've use the supplied compiled version, the .bubble_ reference is .e. Example:

$(infoBubble.e).find("#yourdiv").live("click",function(event) {
    console.log(event.target.id);
});



回答3:


google.maps.event.addDomListener(infoBubble.bubble_, 'click', function() {
    alert("Ooo..!");
});

It works!




回答4:


To further improve on @Marius' answer, as well as update it for the current versions of jQuery (given that I can see that the OP has jQuery available), try the following to target the click event on a specific element within your infoBubble:

$(infoBubble.bubble_).on("click", "button.close", function() {
    console.log("Button with class .close clicked.");
});

If you need to pass data to your function, one option is to use data-* attributes and grab it through the event target, as follows:

Example JS for your InfoBubble content:

var myVariable = 10;
var infoBubbleContentString = '<span class="my-style" data-id="' + myVariable + '">Button text</span>';

Event handler:

$(infoBubble.bubble_).on("click", ".my-style", function (e) {
    if ($(e.target).data('id')) {
        var myVariableValue = $(e.target).data('id'); // myVariableValue will equal 10
    }
});


来源:https://stackoverflow.com/questions/12368902/google-maps-api-event-listener-for-infobubble-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!