gmap监听器无法正常工作

时间:2013-04-10 21:56:52

标签: javascript jquery ajax json google-maps

我面临一个让我疯狂的问题...... 我确定你会比我更新鲜,理解为什么第二个标记听众不能正常工作。 : - (

在这段代码中,我从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...
}

非常感谢提前! 塞德里克。

1 个答案:

答案 0 :(得分:0)

如果要在非gmaps对象中添加事件侦听器,则应使用google.maps.event.addDomListener

所以你可以试试这个:

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