Gmap监听器不工作

gmap listener not working

本文关键字:工作 监听器 Gmap      更新时间:2023-09-26

我正面临一个让我抓狂的问题…
我相信你会比我更清楚为什么第二个标记侦听器不起作用。: - (

在这段代码中,我从JSON格式的Ajax查询中获得一些项目。

下面是javascript代码:
// Get all items in JSON format
function getItems()
{
    // Ajax call
    $.getJSON("/index/test", function(data) {
        createMenu(data);
        fillMap(data);
    });
}
function fillMap(data){
    // For each
    $.each(data, function(key, item) {
        // Create markers
        var latLon = new google.maps.LatLng(item.lat,item.lon);
        marker = new google.maps.Marker({
            position:     latLon,
            map:         map,
            title:        'Index: ' + item.id,
        });
        // Set marker on the map
        marker.setMap(map);
        // Listener 1
        google.maps.event.addListener(marker, "click", function() {
            map.setCenter(marker.getPosition());
        });
        // Listener 2 - 
        google.maps.event.addListener($('#resultList-'+item.id)[0], 'click', function() {
            map.setCenter(marker.getPosition());
        });
     });
}

//Create the HTML menu
function createMenu(data){
    var items = [];
    //For each items
    $.each(data, function(key, item) {
        var imgHtml = '<img class="shadow" src="../images/item.png" height="48" width="48" alt="photo">';
        // Create the HTML li tag
        var html = '<li id="resultList-' + item.id + '" class="resultList">' + imgHtml + item.nom + ' ' + item.prenom + '<br/>' + item.adresse + '<br/>' + item.ville + ', ' + item.pays + '</li>';
        items.push(html);
    });
    // Fill the div
    $('<ul/>', {
        'id': 'resultList',
        'class': 'resultList',
        html: items.join('')
    }).appendTo('#divList');
    //End...
}

提前感谢!塞德里克。

如果你想在非gmap对象中添加一个事件监听器,你应该使用google.maps.event.addDomListener

你可以试试:

google.maps.event.addDomListener(document.getElementById('resultList-' + item.id), 'click', function() {
    map.setCenter(marker.getPosition());
});