【问题标题】:google map v3 how fitbounds with zoom on user's location谷歌地图v3如何缩放用户位置
【发布时间】:2012-02-05 21:48:46
【问题描述】:

我正在使用 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);
    }

【问题讨论】:

    标签: google-maps google-maps-api-3 game-center fitbounds


    【解决方案1】:

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

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

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

    function updateCenter() { 
        googleMap.setCenter(userPinLoc);
    }
    

    【讨论】:

    • 如果没有,请发布您用于地图内容的所有 JS
    • 我再次看到问题,我发现制作中心有效,但如果任何引脚脱离上下文,它不会设置自动缩放级别。我已经更新了我的代码检查 setInitialzoom 方法
    • 您之前接受了我对您的问题的回答。你真的应该为这个其他问题发布一个新问题,而不是仅仅编辑你原来的问题并且不接受我的回答。
    • 好的,抱歉 :) 感谢亲爱的帮助,我创建了新问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多