如何修复页面加载时谷歌地图的缩放

How to fix zoom of Google map on page load

本文关键字:谷歌地图 缩放 加载 何修复      更新时间:2023-09-26

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

"缩放"设置为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>

由于,您的地图会缩小

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

它试图拟合边界以包括您添加的点,而中心保持在init中设置的0,0。

相反,使用类似的setCenter

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