Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix zoom of Google map on page load

I want to fix the zoom of google map on page load. And then I need to zoom in/zoom out it. I have put the code below.

Zoom is set as 6. But it always goes to maximum zoom while loading the web page. Can't fix the zoom to 6 when loading the map.

<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>
like image 939
Dhanya Avatar asked Nov 02 '25 18:11

Dhanya


1 Answers

Your maps zooms out because of

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

It tries to fit the bounds to include the point you add, while the center stays at 0,0 as set in the init.

Instead use setCenter like

    center = bounds.getCenter();
    map.setCenter(center);
like image 83
Bas van Stein Avatar answered Nov 04 '25 09:11

Bas van Stein