How to overwrite Google Map initialized opts with fitBounds();

1.2k views Asked by At

I've been searching for a way to overwrite a Google map's center latlng and zoom using the fitBounds() method. As you can see I have an array of latlng coordinates which I would like to all fit within the map at the correct zoom.

Annoyingly, the map only ever takes the latlng coordinates of the center attribute when the map is initialized. Please help, I can't see what I'm doing wrong. Thanks

    function initialize() {
    var centrelatlng = new google.maps.LatLng(52.474, -1.868);

    var myOptions = {
        zoom:11,
        center: centrelatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';

    var hotels = [
        ['ibis Birmingham Airport', 52.452656, -1.730548, 4],
        ['ETAP Birmingham Airport', 52.452527, -1.731644, 3],
        ['ibis Birmingham City Centre', 52.475162, -1.897208, 2]
    ];

    var latLngs = [];
    var hotel;
    for (var i = 0; i < hotels.length; i++) {
        hotel = hotels [i];
        var myLatLng = new google.maps.LatLng(hotel[1], hotel[2]);
        latLngs[i] = myLatLng;
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: image,
            title: hotel[0],
            zIndex: hotel[3]
        });
    }

    var latlngbounds = new google.maps.LatLngBounds();
    latLngs.each(function(n){
        latlngbounds.extend(n);
    });
    map.setCenter(latlngbounds.getCenter());
    map.fitBounds(latlngbounds); 

};

Please note that you must scroll down code viewer to see all code.

1

There are 1 answers

1
puckhead On BEST ANSWER

Don't set the center in myOptions, and also remove map.setCenter(latlngbounds.getCenter()); and you should be good to go.