中心Google地图InfoWindow On Load

时间:2013-08-18 23:08:08

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

我在页面加载时将InfoWindow置于中心位置时出现问题。在加载时,地图以标记为中心,将InfoWindow关闭屏幕(我的地图容器的高度很短)。

现在单击标记会使InfoWindow上的地图重新居中,以使其看起来与我想要的完全一致。在这种情况下,我甚至尝试触发marker.click触发器来实现负载解决方案,但没有运气。我错过了什么?

JSFIDDLE:http://jsfiddle.net/q9NTS/7/

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
    var geocoder = new google.maps.Geocoder();
    var marker;
    var infoWindow;
    var map;
    function initialize() {
        var mapOptions = {
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
        setLocation();
    }

    function setLocation() {
        var address = '@(Model.Event.Address)' + ', ' + '@(Model.Event.City)' + ', ' + '@(Model.Event.State)' + ' ' + '@(Model.Event.Zip)';
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var position = results[0].geometry.location;
                marker = new google.maps.Marker({
                    map: map,
                    position: position,
                    title: '@(Model.Event.Venue)'
                });
                map.setCenter(marker.getPosition());

                var content = 'blah';
                infoWindow = new google.maps.InfoWindow({
                    content: content
                });

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

                //infoWindow.open(map, marker); doesn't work
                google.maps.event.trigger(marker, 'click'); //still doesn't work
            }
            else {
                //
            }
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

1 个答案:

答案 0 :(得分:6)

您显然只需要等待更长时间才能触发点击事件。

// wait until the map is idle.
google.maps.event.addListenerOnce(map, 'idle', function() {
  setTimeout(function() {
    // wait some more (...)
    google.maps.event.trigger(marker, 'click'); //still doesn't work
  },2000);
});

fiddle