首页 > 解决方案 > 如何在谷歌地图的页面加载中打开信息窗口

问题描述

我在谷歌地图上有一个标记。它有一个包含一些内容的信息窗口。我希望它应该在页面呈现不在点击事件中时自动打开。

   function initMap() {
        var myLatLng = new google.maps.LatLng(22.804270950051844, 86.18359432304942),
            myOptions = {
                zoom: 14,
                center: myLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            },
            map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
            marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                icon: 'http://maps.google.com/mapfiles/ms/micons/green.png',
                label: "1",
            });
        var contentString = 'no 1';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        marker.addListener('click', function () {
            infowindow.open(map, marker);
        });
         infowindow.open(map, marker);
        marker.setMap(map);
    }

标签: javascriptgoogle-maps

解决方案


不要放入侦听器,而是放入正文 initMap 代码

  function initMap() {
        var myLatLng = new google.maps.LatLng(22.804270950051844, 86.18359432304942),
            myOptions = {
                zoom: 14,
                center: myLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            },
            map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
            marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                icon: 'http://maps.google.com/mapfiles/ms/micons/green.png',
                label: "1",
            });

        var contentString = 'no 1';

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

        infowindow.open(map, marker);

    }

如果您遇到重叠问题,请尝试分配一个适当的新位置,例如:(position默认情况下包含此信息窗口所锚定的对象的 LatLng)

        var infowindow = new google.maps.InfoWindow({
            content: contentString,
            position: new google.maps.LatLng(22.80427+ 0.000005 , 86.18359+ 0.000005)
        });

推荐阅读