如何在Google地图中切换多个叠加层?

时间:2012-05-04 08:43:03

标签: javascript jquery html google-maps

我有一个点击事件,可以远程抓取坐标,将它们放在地图上,然后用折线连接它们。我有其他同样的点击事件,但希望将它们保存为单独的图层,以便用户可以切换以查看他们所做的每次点击。有没有人知道将它们分开进行分组的好方法呢?

到目前为止,这是我的代码:

drawPoints: function (points, color) {
    $.each(points, function (key, val) {
        var location = new google.maps.LatLng(val.Latitude, val.Longitude);
        MyTest.addMarker(location, val.Name, val.Description);
        MyTest.coordinates.push(location);
    });

    this.path = new google.maps.Polyline({
        path: MyATest.coordinates,
        strokeColor: color,
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

    this.path.setMap(this.googlemap);
},

addMarker: function (location, title, html) {
    var marker = new google.maps.Marker({
        position: location,
        map: this.googlemap,
        title: title,
        html: html
    });

    this.markers.push(marker);
},

// Removes the overlays from the map, but keeps them in the array
clearOverlays: function () {
    if (this.markers) {
        for (i in this.markers) {
            this.markers[i].setMap(null);
        }
    }
},

// Shows any overlays currently in the array
showOverlays: function () {
    if (this.markers) {
        for (i in this.markers) {
            this.markers[i].setMap(map);
        }
    }
},

1 个答案:

答案 0 :(得分:1)

你已经将它们保存在这个标记中 - 这是一个很好的开始。现在您需要做的就是为每个标记定义一个click侦听器函数:

for(i in this.markers) {
    google.maps.addListener(this.markers[i], function() {
        this.markers[i].clicked = true; });
}

然后,每当用户想要仅切换他们点击的标记时,循环遍历您的标记(就像您正在做的那样)并将setMap设置为null,其中this.markers [i] .clicked === undefined。