How to center and scale multiple markers on Google Maps V3

I am using the following code:

 var geocoder;
    var map;
    var markers = [];
    function initialize() {
        geocoder = new google.maps.Geocoder();
        // var latlng = new google.maps.LatLng(51.733833,0.351563);
        var latlng = new google.maps.LatLng(53.590875,-2.279663);
        // var latlng = new Array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
        var myOptions = {
            zoom: 7,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        addPostCode('EX4 5SP');
        addPostCode('EX16 6LH');
        addPostCode('M1 2AP');

}

I have found some examples of how to achieve this. In the following code: Google MAP API v3: center and scale the displayed markers to achieve this, use the following code,

// map: an instance of GMap3
// latlng: an array of instances of GLatLng
var latlngbounds = new google.maps.LatLngBounds();
latlng.each(function(n){
   latlngbounds.extend(n);
});
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

The problem is that I need to use zip codes to display the location on the map. Is it possible to create an array of GLatLng instances from a zip code and then use the above code to scale and center multiple markers on a map?

+4
source share
2 answers

//locationsColl

var latlng = [];
_.forEach(locationsColl, function (address) {
    latlng.push(address);
});

var latlngbounds = new google.maps.LatLngBounds();
_.forEach(latlng,function (n) {
    latlngbounds.extend(n);
});
// center map to central point between markers
map.setCenter(latlngbounds.getCenter());
// set zoom to fit all coord
map.fitBounds(latlngbounds);
+1

All Articles