Sheraz
Sheraz

Reputation: 71

Multiple markers map having zoom in issue for single marker

below is the code for displaying a Google map with multiple markers. The markers data is coming from DB so it can contain 1 location or multiple locations.
For multiple markers the map is centered and auto zoomed. The problem is if there is only 1 marker , the map zoom in to maximum level. Can someone guide me how to fix the zooming for single marker.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var markers = <?php echo $marker;?>;

$(document).ready(function() {
    // Handler for .ready() called.

    initializeMaps();
});

function initializeMaps() {
    var myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        zoom: 6
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    var infowindow = new google.maps.InfoWindow(); 
    var marker, i;
    var bounds = new google.maps.LatLngBounds();

    for (i = 0; i < markers.length; i++) { 
        var pos = new google.maps.LatLng(markers[i][1], markers[i][2]);
        map.setCenter(pos);
        if(i==0){
            map.setZoom(5);
        }

        bounds.extend(pos);
        marker = new google.maps.Marker({
            position: pos,
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {

                infowindow.setContent(markers[i][0]);
                infowindow.open(map, marker);
                //alert('asdfsdfdsaf');

            }
        })(marker, i));
    }
    map.fitBounds(bounds);
}
</script>


<div id="map_canvas" style="width:100%; height:400px"></div>

Upvotes: 0

Views: 465

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117354

call map.fitBounds(bounds) only when there are more than 1 marker

Upvotes: 1

Related Questions