Google MAP API v3: Center & Zoom on displayed markers

I use the following code to set markers on my map:

  var latLngs = []
  $.each(locations.markers, function(i, m){
   var myLatLng = new google.maps.LatLng(m.latitude, m.longitude);
   latLngs[i] = myLatLng                                          
   var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    shadow: shadow,
    icon: image,
    shape: shape,
    zIndex: i

The markers show up on my map. Now I would like to center & zoom the map on these markers. How can I accomplish this? I have tried:


The console.log of latLngs gives out:

 [(46.793182, 7.146903) { b=46.793182,  more...}, (46.8077779, 7.1709386) { b=46.8077779,  more...}]

But it doesn't seem to work, and I get no error in the console. What am I doing wrong?



I've also find this fix that zooms to fit all markers

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
    latlngbounds = new google.maps.LatLngBounds();


// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);


In case you prefer more functional style:

// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
    return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());


Try this works...

$(function() {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var latlng_pos=[];
        var j=0;
            latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                // position: new google.maps.LatLng(-35.397, 150.640),
                map: map
        // map: an instance of google.maps.Map object
        // latlng: an array of google.maps.LatLng objects
        var latlngbounds = new google.maps.LatLngBounds( );
        for ( var i = 0; i < latlng_pos.length; i++ ) {
            latlngbounds.extend( latlng_pos[ i ] );
        map.fitBounds( latlngbounds );


for center and auto zoom on display markers

// map: an instance of google.maps.Map object

// latlng_points_array: an array of google.maps.LatLng objects

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

    for ( var i = 0; i < latlng_points_array.length; i++ ) {
        latlngbounds.extend( latlng_points_array[i] );

map.fitBounds( latlngbounds );


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.