Google Maps API: zoom into the group of markers

Asked

Viewed 269 times

1

I have a map where the user looks for points like bakeries, registered supermarkets around an area.

I would like, when loading the map, the API to grab all the registered points zoomed in that displayed all of them.

I tried to use fitBounds, but nothing is happening. Can you explain why?

  var themap;
  var allmarkers=[];
  var directionsService;
  var directionsDisplay;
  var empreendimento_position;

  function initialize() {

    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    var local_geo=$('#localizacao_geo').html();
    local_geo=local_geo.trim().substr(2,local_geo.length);

    if(local_geo){
        local_geo=JSON.decode(local_geo);
    }

    var mapOptions = {
      center: { lat: -34.397, lng: 150.644},
      zoom: 14,
      scrollwheel: false
    };     

    if(isMobile.any()){
        mapOptions.draggable=false;
        mapOptions.streetViewControl=false;
    }

    if(local_geo){
        var pos=local_geo[0].position.replace("(","");
        pos=pos.replace(")","");
        pos=pos.split(',');

        mapOptions.center={ lat: parseFloat(pos[0]), lng: parseFloat(pos[1])};
    }

    var map =themap= new google.maps.Map($('.localizacao_map').get(0),
        mapOptions);
    var link_empreendimento;  

    directionsDisplay.setMap(map);     


    if(local_geo){
        var num_pins=0;
        $(local_geo).each(function(index,item){             
            var pos=item.position.replace("(","");
            pos=pos.replace(")","");
            pos=pos.split(',');    
            var latlngbounds = new google.maps.LatLngBounds();    
            var marker = new google.maps.Marker({
              position: new google.maps.LatLng(pos[0],pos[1]),
              icon: webroot('img/icons/'+item.type+'.png'),
              map: map,
              dados:item
            });    
            latlngbounds.extend(marker.position);    
            if(marker.dados.type=='empreendimento'){
                empreendimento_position=marker.dados.position;
            }else{
                num_pins+=1;
            }

            allmarkers.push( marker );

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

              map.setCenter(marker.getPosition());

            });

        });

        sync_types();
    }
    map.fitBounds(latlngbounds);
  }

  function loadScript() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
          '&signed_in=true&callback=initialize&thekey=<?php echo $mapskey ?>';
      document.body.appendChild(script);
  }
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.