谷歌地图setVisible不是一个功能

时间:2011-03-31 12:08:48

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

这是我的markers[]数组:

partnerMarkers = [
        // London
        { lat: 51.515482718, lng: -0.142903122, name: "London", content: "Our home town and international hub." },
// Dubai
        { lat: 25.2644444, lng: 55.3116667, name: "Middle East", content: "Dubai desc" }
];

我有这个功能,循环遍历标记数组(由其他地方的按钮触发):

function toggle_layer(markers) {
    for (var i=0; i<markers.length; i++) {
        markers[i].setVisible(false);
    }
}

我得到markers[i].setVisible is not a function - 但是这样可以正常工作:

function toggle_layer(markers) {
    for (var i=0; i<markers.length; i++) {
        console.log(markers[i]);
    }
}

为什么setVisible在这种情况下不起作用?

3 个答案:

答案 0 :(得分:2)

以下是JSFiddle Demo:

似乎您的标记只是对象而不是google.maps.Markers,因此它内部没有setVisible()函数。您基本上希望将对象中的数据转换为google.maps.Marker对象。我创建了一个全局数组gooMarker来保存标记。通过单击地图下方的链接,它将隐藏标记。以下是创建标记然后隐藏它们的方法:

HTML标记:

<div id='parent'>
    <div id="map_canvas" style="width: 650px; height: 550px;"></div>
</div>
<div id='hidemark'>Click to hide markers</div>

JavaScript + Google Map V3 API:

var map;
var gooMarker = [];

var partnerMarkers = [
   {
    lat: 51.515482718,
    lng: -0.142903122,
    name: "London",
    content: "Our home town and international hub."},
    {
    lat: 25.2644444,
    lng: 55.3116667,
    name: "Middle East",
    content: "Dubai desc"}
];

function initialize() {

    var london = new google.maps.LatLng(51.5, 0);

    var myOptions = {
        backgroundColor: '#FFFFF',
        zoom: 2,
        center: london,
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map_canvas = document.getElementById("map_canvas");

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

    for (var i = 0; i < partnerMarkers.length; i++) {
        gooMarker.push(new google.maps.Marker({
            position: new google.maps.LatLng(partnerMarkers[i].lat, partnerMarkers[i].lng),
            map: map,
            title: partnerMarkers[i].name
        }));
    }
}

function hideMarkers(){
    for(var i=0; i<gooMarker.length; i++){
        gooMarker[i].setVisible(false);
    }
}

document.getElementById('hidemark').onclick = hideMarkers;

window.onload = initialize;

答案 1 :(得分:2)

kjy112就在现场,简化为直接插入代码:

partnerMarkers = [
// London
    new google.maps.Marker(
    { position: new google.maps.LatLng(51.515482718, -0.142903122), 
    title: "London - Our home town and international hub." },
// Dubai
    new google.maps.Marker(
    { position: new google.maps.LatLng(25.2644444, 55.3116667), 
    title: "Middle East - Dubai desc" }
];

答案 2 :(得分:0)

我没有在你的代码中看到Marker构造函数

new google.maps.Marker