如何在页面加载时修复Google地图的缩放

时间:2015-11-12 07:24:26

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

我想在页面加载时修复谷歌地图的缩放。然后我需要放大/缩小它。我把代码放在下面。

缩放设置为6.但加载网页时始终进行最大缩放。加载地图时无法将缩放固定为6.

<script type="text/javascript">
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
        new google.maps.Size(32, 32), new google.maps.Point(0, 0),
        new google.maps.Point(16, 32));
    var center = null;
    var map = null;
    var currentPopup;
    var bounds = new google.maps.LatLngBounds();
    function addMarker(lat, lng, info) {
        var pt = new google.maps.LatLng(lat, lng);
        bounds.extend(pt);
        var marker = new google.maps.Marker({
            position: pt,
            icon: icon,
            map: map
        });
        var popup = new google.maps.InfoWindow({
            content: info,
            maxWidth: 300
        });
        google.maps.event.addListener(marker, "click", function() {
            if (currentPopup != null) {
                currentPopup.close();
                currentPopup = null;
            }
            popup.open(map, marker);
            currentPopup = popup;
        });
        google.maps.event.addListener(popup, "closeclick", function() {
            map.panTo(center);
            currentPopup = null;
        });
    }
    function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(0, 0),
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
            },
            navigationControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.SMALL
            }
        });
        <?  
            $lat='1.281776';
            $lon='103.844945';
            $name= $lat;
            $desc= $lon;
            echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
        ?>
        center = bounds.getCenter();
        map.fitBounds(bounds);
    }
</script>

1 个答案:

答案 0 :(得分:3)

您的地图因

而缩小
    center = bounds.getCenter();
    map.fitBounds(bounds);

它尝试拟合边界以包含您添加的点,而中心保持在初始化设置的0,0。

而是使用setCenter之类的

    center = bounds.getCenter();
    map.setCenter(center);