javascriptphpgoogle-maps

google maps api initial zoom error


I have the following code:

<?php if($_GET['postcode']){ ?>

//alert(<?php echo $_GET['postcode'];?>)

<?php }?>

      function initialize() {
        var mapOptions = {
          zoom: 6,
          center: new google.maps.LatLng("<?php echo $_GET['postcode'];?>"),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
        map.setTilt(45);

        var addressArray = new Array("<?php echo $_GET['postcode'];?>");
        var geocoder = new google.maps.Geocoder();

        var markerBounds = new google.maps.LatLngBounds();

        for (var i = 0; i < addressArray.length; i++) {
        geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

        var contentString = '<div id="content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h4 id="firstHeading" class="firstHeading">HELLO</h4>'+
        '<div id="bodyContent">'+
        '<p><b>Hello!!</b>' + <?php echo $_GET["order_id"];?> + '</p>'+
        '</div>'+
        '</div>';

        var infowindow = new google.maps.InfoWindow({
        content: contentString
        });

        var marker = new google.maps.Marker({
        map: map, 
        title:"Order Number",
        position: results[0].geometry.location
        });

        markerBounds.extend(results[0].geometry.location);
        map.fitBounds(markerBounds);

        google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
        });

        } else {
        alert("Geocode was not successful for the following reason: " + status);
        }
        });
        }
      }

      function loadScript() {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
            'callback=initialize';
        document.body.appendChild(script);
      }

      window.onload = loadScript;
    </script>

For some reason, when the map loads up, the zoom level is full, so its zoomed right into the marker. I've tried adjusting the zoom level on the initialize section, but I have had no joy. My guess is, that it has something to do with the marker bounds. Anyone know how to adjust the zoom so that it is not fully zoomed on the marker?


Solution

  • for some reason, when the map loads up, the zoom level is full, so its zoomed right into the marker.

    If you have a bounds object with one LatLng in it, it should zoom in as far as possible. From the documentation:

    fitBounds(bounds:LatLngBounds)  None    Sets the viewport to contain the given bounds.
    

    If you only have one marker, don't use fitBounds, use .setCenter (on the coordinates of the marker, .setZoom (to your desired zoom level).

    If your code needs to handle both cases (one marker or several markers), count the markers you add to the bounds, if the number is one use .setCenter/.setZoom, if it is more than one, use .fitBounds.

    code snippet (2 markers)

    var markerCount = 0;
    function initialize() {
            var mapOptions = {
              zoom: 6,
              center: new google.maps.LatLng(40.731,-73.997),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
            map.setTilt(45);
    
            var addressArray = ["10018","07102"];
            var geocoder = new google.maps.Geocoder();
    
            var markerBounds = new google.maps.LatLngBounds();
    
            for (var i = 0; i < addressArray.length; i++) {
            geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
    
            var contentString = '<div id="content">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h4 id="firstHeading" class="firstHeading">HELLO</h4>'+
            '<div id="bodyContent">'+
            '<p><b>Hello!!</b>' + i + '</p>'+
            '</div>'+
            '</div>';
    
            var infowindow = new google.maps.InfoWindow({
            content: contentString
            });
    
            var marker = new google.maps.Marker({
            map: map, 
            title:"Order Number",
            position: results[0].geometry.location
            });
    
            markerBounds.extend(results[0].geometry.location);
            markerCount++;
            if (markerCount<2) {
              map.setCenter(marker.getPosition());
              map.setZoom(15);
            } else {
              map.fitBounds(markerBounds);
            }
    
            google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
            });
    
            } else {
            alert("Geocode was not successful for the following reason: " + status);
            }
            });
            }
          }
    
          function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&' +
                'callback=initialize';
            document.body.appendChild(script);
          }
    
          window.onload = loadScript;
        </script>
    /* 
     * Always set the map height explicitly to define the size of the div element
     * that contains the map. 
     */
    #map_canvas {
      height: 100%;
    }
    
    /* 
     * Optional: Makes the sample page fill the window. 
     */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <html>
    <head>
    </head>
    <body>
    <div id="map_canvas"></div>
     </body>
    </html>

    code snippet (1 marker)

    var markerCount = 0;
    function initialize() {
            var mapOptions = {
              zoom: 6,
              center: new google.maps.LatLng(40.731,-73.997),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
            map.setTilt(45);
    
            var addressArray = ["10018"];
            var geocoder = new google.maps.Geocoder();
    
            var markerBounds = new google.maps.LatLngBounds();
    
            for (var i = 0; i < addressArray.length; i++) {
            geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
    
            var contentString = '<div id="content">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h4 id="firstHeading" class="firstHeading">HELLO</h4>'+
            '<div id="bodyContent">'+
            '<p><b>Hello!!</b>' + i + '</p>'+
            '</div>'+
            '</div>';
    
            var infowindow = new google.maps.InfoWindow({
            content: contentString
            });
    
            var marker = new google.maps.Marker({
            map: map, 
            title:"Order Number",
            position: results[0].geometry.location
            });
    
            markerBounds.extend(results[0].geometry.location);
            markerCount++;
            if (markerCount<2) {
              map.setCenter(marker.getPosition());
              map.setZoom(15);
            } else {
              map.fitBounds(markerBounds);
            }
    
            google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
            });
    
            } else {
            alert("Geocode was not successful for the following reason: " + status);
            }
            });
            }
          }
    
          function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&' +
                'callback=initialize';
            document.body.appendChild(script);
          }
    
          window.onload = loadScript;
        </script>
    /* 
     * Always set the map height explicitly to define the size of the div element
     * that contains the map. 
     */
    #map_canvas {
      height: 100%;
    }
    
    /* 
     * Optional: Makes the sample page fill the window. 
     */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <html>
    <head>
    </head>
    <body>
    <div id="map_canvas"></div>
     </body>
    </html>