Google通过点击infowindow内的链接来映射api打开新的信息窗口

时间:2016-04-08 11:13:21

标签: javascript google-maps infowindow

我试图关闭旧的infowindow并打开新的infowindow(或替换此infowindow上的内容),但我不能让它工作。我尝试谷歌它。 如果我现在试试谷歌Chrome浏览器开发工具的控制台说"未捕获类型错误:无法读取属性'关闭'未定义"。

<script>
var map;
var marker;
var markerInfoWindow;

function intMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(60.3000216, 24.944929),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    // Create a new marker
    var marker = new google.maps.Marker({ draggable: true, icon: 'images/new_marker.png' });
    var markerInfoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(map, 'click', function(event) {
        marker.setPosition(event.latLng);
        marker.setMap(map);

        var contentString = "<a href='#' onclick='openNew();'>Click here to open new infowindow!</a>";
        var markerInfoWindow = new google.maps.InfoWindow({
            content: contentString
        });            
        markerInfoWindow.open(map, marker);
        marker.addListener('click', function() {
            markerInfoWindow.open(map, marker);
        });
    });
}         
    google.maps.event.addDomListener(window, "load", intMap);

    function openNew() {
        markerInfoWindow.close();
        var contentString = "Open this infowind when clicked link";
        var markerInfoWindowNew = new google.maps.InfoWindow({
            content: contentString
        });  
    }
</script>

1 个答案:

答案 0 :(得分:1)

变量markerInfoWindow的范围存在问题 - 在您的代码中创建新的本地隐藏外部

var map;
var marker;
var markerInfoWindow;

function intMap() {

    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(60.3000216, 24.944929),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    // Create a new marker
    marker = new google.maps.Marker({
        draggable: true,
        icon: 'images/new_marker.png'
    });
    markerInfoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(map, 'click', function(event) {
        marker.setPosition(event.latLng);
        marker.setMap(map);

        var contentString = "<a href='#' onclick='openNew();'>Click here to open new infowindow!</a>";
        markerInfoWindow = new google.maps.InfoWindow({
            content: contentString
        });
        markerInfoWindow.open(map, marker);
        marker.addListener('click', function() {
            markerInfoWindow.open(map, marker);
        });
    });
}
google.maps.event.addDomListener(window, "load", intMap);

function openNew() {
    markerInfoWindow.close();
    var contentString = "Open this infowind when clicked link";
    markerInfoWindow = new google.maps.InfoWindow({
        content: contentString
    });
    markerInfoWindow.open(map, marker);
}