简体   繁体   中英

How to center and zoom multiple markers on Google Maps V3

I use 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 found some example how to achieve this In the following code: Google MAP API v3: Center & Zoom on displayed markers to achieve this, the following code is used.

// 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 Postcodes to display the location on the map. Is is possible to create an array of instances of GLatLng from a postcode and then use the above code to zoom and center the multiple markers on map?

GClientGeocoder can take a postal code and return a GLatLng: see https://groups.google.com/forum/#!topic/google-maps-api/JN8OW5Tyaws .

For centering multiple markers, see Find center of multiple locations in Google Maps

Yes this is V2-- the GLatLng threw me. The same functionality exists in V3: https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

//locationsColl containts list of co ordinates

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM