如何在循环中创建的多个标记内插入函数

时间:2015-06-22 15:43:13

标签: javascript google-maps google-maps-api-3

我正在尝试在谷歌地图中插入多个标记,将它们添加到地图中并带有一个循环;问题是我在标记的infoWindow()内有一个函数,但是如果我尝试使用只有两个位置,函数在两个标记中调用,但只有最后一个值,换句话说,该函数只接受最后一个参数。这是代码

var luoghi = {"city":[
    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" },
    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" }
]} ; 

var marker2,i;          
    for( i in luoghi.city){
        lat = luoghi.city[i].lat;
        lng= luoghi.city[i].lng;
        var myLatlng = new google.maps.LatLng(lat,lng);

        marker2 = new google.maps.Marker({
            position: myLatlng,
            map: map,
            animation: google.maps.Animation.DROP,
            title: ''+myLatlng
        });

        google.maps.event.addListener(marker2,'click',(function(marker2){
            return function(){
                if(infoWindow) infoWindow.close();
                var contentString = '<p>Visiona meteo e foto utenti flickr in questa zona</p>'+
                                    '<input type= "button" value="Visualizza" onclick="visualizza()">';
                infoWindow = new google.maps.InfoWindow({
                    content: contentString
                });
                infoWindow.open(map,marker2);
        }
    })(marker2));
}

函数 visualizza()是正确的,问题是在循环中,我无法弄清楚为什么它不能像我期望的那样工作。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您有范围问题。试试这个:

var luoghi = {"city":[
    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" },
    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" }
]} ;

var marker = {};
var infoWindow = {};

for(var i in luoghi.city){
    var lat = luoghi.city[i].lat;
    var lng= luoghi.city[i].lng;
    var myLatlng = new google.maps.LatLng(lat,lng);

    marker[i] = new google.maps.Marker({
        position: myLatlng,
        map: map,
        animation: google.maps.Animation.DROP,
        title: ''+myLatlng
    });

   infoWindow[i] = new google.maps.InfoWindow({
        content: '<p>Visiona meteo e foto utenti flickr in questa zona</p><input type= "button" value="Visualizza" onclick="visualizza()">'
    });

    google.maps.event.addListener(marker[i], 'click', function(marker){
        infoWindow.open(map, marker);
    }(marker[i]));
}