0

我正在使用 google v3,我想以 userPinLoc 对象为中心来调整边界,我有以下代码

 var bounds = new google.maps.LatLngBounds();
            bounds.extend(userPinLoc)// wants to center on userPinLocation
            for (i in nearestEntitiesToZoom) {
                    entity = nearestEntitiesToZoom[i];
                    var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
                    bounds.extend(googleLatLng);
                }

                bounds.extend(userPinLoc);
                //googleMap.setCenter(userPinLoc) this not working

googleMap.fitBounds(bounds);

更新后的任何快速修复我正在粘贴新代码

function setInitialZoom() {
        mapZoom = googleMap.getZoom(); 
        var bounds = new google.maps.LatLngBounds();
        bounds.extend(userPinLoc);
        for (i in nearestEntitiesToZoom) {
            entity = nearestEntitiesToZoom[i];
            var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
            bounds.extend(googleLatLng);
        }

        google.maps.event.addDomListener(googleMap, 'bounds_changed', function() {
            googleMap.setCenter(userPinLoc);
        });

        googleMap.fitBounds(bounds);
        setTimeout(function() {
            google.maps.event.clearListeners(googleMap, 'bounds_changed');
        }, 3000);
    }
4

1 回答 1

0

从当前位置移除 setCenter。当地图的边界发生变化时,您需要有一个事件侦听器。我认为当您调用 fitBounds 时,您必须等待它重新绘制才能调整中心。一种方法是使用超时,但您可以简单地将其添加到您的初始化函数中:

google.maps.event.addDomListener(googleMap, 'bounds_changed', updateCenter);

然后创建一个新函数来更新中心,该函数采用 userPinLoc 值(需要是全局变量):

function updateCenter() { 
    googleMap.setCenter(userPinLoc);
}
于 2012-01-09T10:46:03.167 回答