谷歌地图API V3:信息窗口在页面加载时自动打开

23
我正在开发一个项目,使用Google Maps api-v3,在地图上会有几个带有信息的地点标记,我将这些信息存储在一个 InfoWindow 中。
我想知道是否有一种方法可以在页面加载时自动打开 InfoWindow(即自动打开而无需用户交互)。
在网上搜索,我似乎只能找到需要绑定事件监听器的方法,但是 InfoWindow 对象似乎只有鼠标事件。
有人知道解决方法吗?
5个回答

32

不确定我完全理解你的问题,但这对我来说可以使用硬编码的LatLng:

var infoWindow = null;
function initialize() 
{
    infoWindow = new google.maps.InfoWindow();
    var windowLatLng = new google.maps.LatLng(43.25,-68.03);
    infoWindow.setOptions({
        content: "<div>This is the html content.</div>",
        position: windowLatLng,
    });
    infoWindow.open(map); 
} // end initialize

google.setOnLoadCallback(initialize);

信息窗口正好落在我的标记上。有没有办法计算经度差异,以便将信息窗口放置在标记正上方? - Edward

11

我回答这个问题有些晚,但我想分享一些东西。我也搜索了解决方案,甚至从上面的解决方案中没有得到可用的方法。然后我自己尝试并得到了自己的解决方案(我不是专家,我的想法可能不好,但对我来说运行良好)。 通常我们会这样做:

var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker) {
return function() {
    infowindow.setContent('some content here');
      infowindow.open(map, marker);
    }
})(marker));

用以下内容替换上述行:

var infowindow = new google.maps.InfoWindow();
infowindow.setContent('some content here');
infowindow.open(map, marker);

不要等待标记的点击事件,只需设置内容并打开它(您必须定义地图和标记,以及信息窗口指向您的标记)。


最简单的解决方案是,在标记点击之外调用它。谢谢Roka。 - Moxet Khan

3

将infowindow.open(map,marker);从google.maps.event.addListener中拿出来。代码应该是这样的:

      var marker = new google.maps.Marker({
      position: myLatlng1,
      map: map,
      title: 'Uluru (Ayers Rock)'

  });

  infowindow.open(map,marker);

  google.maps.event.addListener(marker, 'click', function() {
  });   

2
这是我的代码,它可以在地图上加载信息窗口,并且可以通过鼠标悬停触发。
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
    map: map,
    icon: "/images/map-marker.png",
    draggable: true,
    position: results[0].geometry.location

});
var infowindow = new google.maps.InfoWindow({
    content: "Use pin to point your exact locality"
});
google.maps.event.addListener(marker, 'mouseover', function () {
    infowindow.open(map, marker);
});
infowindow.open(map, marker);

1

function initMap() {
    var cairo = {lat:18.519331, lng: 73.849421};
    var map = new google.maps.Map(document.getElementById('map'), {
        scaleControl: true,
        center: cairo,
        zoom: 15,
    });

    var infowindow = new google.maps.InfoWindow;
    infowindow.setContent('<b>adddress</b>');

    var marker = new google.maps.Marker({map: map, position: cairo});
    infowindow.open(map, marker);
    infoWindow.open(map); 
}
<script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrCByzXY6y5KMSOi9AuqWVf4VYZPyJ5SE&language=hi&region=EG&callback=initMap">
</script>
<div id="map"></div>


最好能解释一下你的代码为什么会起作用。 - Anh Pham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接