所有信息都有相同的数据

时间:2010-09-14 18:12:48

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

我对谷歌地图V3 API相当新,我遇到了一个问题,所有信息都有相同的数据,我使用的代码遍历一系列标记细节,并输出标记加上每个标记的信息窗口。这是我的代码:

    <script type="text/javascript">

(function () {
google.maps.Map.prototype.markers = new Array();
google.maps.Map.prototype.addMarker = function(marker) {
this.markers[this.markers.length] = marker;
};})();

function initialize() {

var latlng = new google.maps.LatLng(37.0691, -8.0312);

    var myOptions = {
    zoom: 12,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var house = 'images/house.png';

    var a = new Array();

    var t =  new Object();
    t.name = "Casa De Cova"
    t.lat =  37.0691
    t.lng =  -8.0312
    t.ico = house
    t.info = 'Casa De Cova Villa'
    a[0] = t;

    var t =  new Object();
    t.name = "Casa Jaquinta"
    t.lat =  37.0450
    t.lng =  -8.0442
    t.ico = house
    t.info = 'Jaquinta Villa'
    a[1] = t;

    var t =  new Object();
    t.name = "Faro Aiport"
    t.lat =  37.016187
    t.lng =  -7.970581
    t.ico = 'images/plane.png'
    t.info = 'The main Airport'
    a[2] = t;


    for (var i = 0; i < a.length; i++) 
    {
        var latlng = new google.maps.LatLng(a[i].lat, a[i].lng);
        map.addMarker(createMarker(a[i].name,latlng,a[i].ico,a[i].info));
    }
}

var counter = 1;

function createMarker(name, latlng, icon, info) 
{
    var marker = new google.maps.Marker({position: latlng, map: map, icon: icon, title: name});

    infowindow = new google.maps.InfoWindow({            
        content: info
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });

    document.getElementById(counter).onclick = function() {
        infowindow.open(map, marker);
    }

    counter++;
    return marker;
}
</script>

如果在'infowindow.open(map,marker);'之前发出'var'声明,问题就有点固定了。如果这样做,那么我可以看到每个窗口及其各自的数据,但是当一个信息窗口被打开时,前一个窗口将不会关闭。

该网站位于:http://www.danhall.co.uk/algarve/map.php

我有点失落,任何帮助都非常感激。

1 个答案:

答案 0 :(得分:3)

绝对使用infowindow的var声明;否则infowindow是全球性的,每次拨打createMarker()时都会覆盖它。

之后,您只需在每次显示时关闭所有打开的信息窗口。以下是我之前解决这个问题的方法:

...
var counter = 1,
    infowindows = [];

function closeInfoWindows()
{
    var i = infowindows.length;
    while(i--)
    {
        infowindows[i].close();
    }
}

function createMarker(name, latlng, icon, info) 
{
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: icon,
        title: name
    });

    var infowindow = new google.maps.InfoWindow({            
        content: info
    });

    infowindows.push(infowindow);

    google.maps.event.addListener(marker, 'click', function ()
    {
        infowindow.open(map,marker);
    });

    document.getElementById(counter).onclick = function ()
    {
        infowindow.open(map, marker);
    }

    counter++;
    return marker;
}