谷歌地图控制按钮

时间:2014-02-14 12:19:52

标签: javascript google-maps button click

http://jsfiddle.net/9hYv4/1

我正在尝试控制地图的标签 - 打开和关闭。

我似乎无法让它发挥作用。见上面的小提琴。

我已经定义了我的按钮来调用函数,并且函数要么显示标签,要么不显示。

这里有一些代码: JAVASCRIPT:

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
    setAllMap(null);
}

// Shows any markers currently in the array.
function showMarkers() {
    setAllMap(map);
}

HTML:

<div id="panel">
    <input onclick="clearMarkers();" checked="checked" type="checkbox" value="Hide Markers"><label>Hide Markers</label>
    <input onclick="showMarkers();" type="button" value="Show All Markers">
</div>

修改

请看这里: http://jsfiddle.net/9hYv4/10/

我不知道我在想什么。我所追求的是一个切换隐藏/显示图标的复选框。因此,当选中时,图标会显示,如果未选中则会隐藏图标。

小提琴和jsbin中的代码运行得相当不错,但是在我发布的小提琴中可以看到,图标分组(markerCluster)不再起作用了。

点击小提琴并缩小以查看。这些图标应该是群集的。

我希望这很清楚?

我非常感谢到目前为止的帮助:)我非常感谢花在帮助我的时间。

总结一下:我使用复选框按钮隐藏/显示图标切换。并恢复群集功能。

非常感谢你:)

1 个答案:

答案 0 :(得分:2)

代码中有一些错误。一个与不可见的变量相关联,应设置为全局:

var map,
    markers = [];

下一个与复选框相关联。显示/隐藏序列与复选框和按钮的状态组合连接(有时复选框未选中,标记被隐藏)。最好对复选框值做出反应。请参阅新功能handleMarkers

function handleMarkers() {
    if (cBox.checked) {
        clearMarkers();
    } else {
        showMarkers();
    }
}

<input onclick="handleMarkers();" id='cBox' checked="checked" type="checkbox" value="Hide Markers"><label>Hide Markers</label>

标记再次显示更改缩放。它与MarkerClusteres相关联。必须添加新的事件监听器:

map.fitBounds(bounds);

google.maps.event.addListener(map, 'zoom_changed', function() {
    console.log('zoom changed!');
    if (cBox.checked) {
        markerCluster.clearMarkers();
    } else {
        markerCluster = new MarkerClusterer(map, markers, clusterOptions);
    }
})

查看更新的example at jsbin:更改了clearMarkers()showMarkers()函数以处理标记群集。

更新:version at jsBin不会创建新的标记群集对象,只是清除/添加现有标记。应该是更好的选择。

缩放更改事件处理程序:仅当markerCluster为空时才恢复标记:

google.maps.event.addListener(map, 'zoom_changed', function() {
    console.log('zoom changed!');
    if (cBox.checked) {
        markerCluster.clearMarkers();
    } else {
        var totArray = markerCluster.getTotalMarkers();
        if (totArray == 0) {
            markerCluster.addMarkers(markers);
        }
        //markerCluster = new MarkerClusterer(map, markers, clusterOptions);
    }
})
相关问题