谷歌地图fitBounds缩放不变

时间:2018-05-08 21:52:10

标签: javascript google-maps

我有一个谷歌地图脚本,但由于fitBounds功能,我无法更改初始缩放。有人可以帮助我已经尝试修改脚本甚至强制缩放,但它不起作用。



jQuery(function($) {
                // Asynchronously Load the map API 
                var script = document.createElement('script');
                script.src = "//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
                document.body.appendChild(script);
            });

            function initialize() {
                var map;
                var bounds = new google.maps.LatLngBounds();
                var mapOptions = {
                    mapTypeId: 'roadmap',  
                    zoom: 14,                  
                    styles: [
    {
        "featureType": "all",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#cecfc4"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "gamma": 0.01
            },
            {
                "lightness": 20
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "saturation": -31
            },
            {
                "lightness": -33
            },
            {
                "weight": 2
            },
            {
                "gamma": 0.8
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "administrative.locality",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "visibility": "off"
            },
            {
                "color": "#ff0000"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#666766"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            },
            {
                "color": "#ff0000"
            }
        ]
    },
    {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [
            {
                "lightness": 30
            },
            {
                "saturation": 30
            },
            {
                "visibility": "on"
            }
        ]
    },
    {
        "featureType": "landscape.man_made",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#f7f5ee"
            }
        ]
    },
    {
        "featureType": "landscape.natural.landcover",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#f7f5ee"
            }
        ]
    },
    {
        "featureType": "landscape.natural.terrain",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#f7f5ee"
            }
        ]
    },
    {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [
            {
                "saturation": 20
            }
        ]
    },
    {
        "featureType": "poi.park",
        "elementType": "geometry",
        "stylers": [
            {
                "lightness": 20
            },
            {
                "saturation": -20
            }
        ]
    },
    {
        "featureType": "poi.park",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#d1cabc"
            }
        ]
    },
    {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [
            {
                "lightness": 10
            },
            {
                "saturation": -30
            }
        ]
    },
    {
        "featureType": "road",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#cec3bc"
            }
        ]
    },
    {
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "saturation": 25
            },
            {
                "lightness": 25
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#d1cabc"
            },
            {
                "visibility": "on"
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "visibility": "off"
            },
            {
                "color": "#ff0000"
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#ff0000"
            }
        ]
    },
    {
        "featureType": "road.highway.controlled_access",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#666766"
            }
        ]
    },
    {
        "featureType": "road.highway.controlled_access",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "road.arterial",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "color": "#666766"
            }
        ]
    },
    {
        "featureType": "road.arterial",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#d1cabc"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "visibility": "off"
            },
            {
                "color": "#ff0000"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#666766"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            },
            {
                "color": "#999897"
            }
        ]
    },
    {
        "featureType": "water",
        "elementType": "all",
        "stylers": [
            {
                "lightness": -20
            }
        ]
    },
    {
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#d1cabc"
            }
        ]
    }
]

                };
                                
                // Display a map on the page
                map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
               
                    
                // Multiple Markers
                var markers = [
                    ['UNDERDOG', -23.5606035,-46.6798997],
                    ['BRAZ ELETTRICA', -23.5644743,-46.6825759],
                    ['CHOPERIA SÃO PAULO', -23.5650709,-46.6833805],
                    ['MEATS', -23.564903,-46.6832477],
                    ['HOUSE OF ALL', -23.5651321,-46.6847573],
                ];
                                    
                // Info Window Content
                var infoWindowContent = [
                    ['<h4 style="color:#000">UNDERDOG</h4>' +
                    '<img src="images/bd01.jpg" class="img-responsive"><br><strong>R. João Moura, 541 – Pinheiros</strong><br>O Underdog é um pequeno bar que serve carnes preparadas na parrilla, o estilo tradicional do churrasco argentino e uruguaio. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'],
                    ['<h4 style="color:#000">BRAZ ELETTRICA</h4>' +
                    '<img src="images/bd02.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 220 - Pinheiros</strong><br>A Braz Elettrica é a irmã hiperativa da Braz. Inaugurada a menos de um ano em Pinheiros  é sucesso absoluto entre os amantes de uma bela redonda acompanhada de uma boa cerveja. E  agora você já pode combinar as opções da Goose Island, incluindo a cerveja especial de aniversário, a 30th com a sua pizza predileta.'],
                    ['<h4 style="color:#000">CHOPERIA SÃO PAULO</h4>' +
                    '<img src="images/bd03.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 315 – Pinheiros</strong><br>Na Choperia São Paulo a cada semana são engatados 20 tipos diferentes às torneiras de chopes inclusive as várias opções de Goose Island, sendo uma delas a cerveja especial de aniversário, a 30th.'],
                    ['<h4 style="color:#000">MEATS</h4>' +
                    '<img src="images/bd04.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 320 - Pinheiros</strong><br>Sob o comando de Paulo Yoller, o Meats oferece um menu inventivo com grande respeito aos clássicos, na duvida do que pedir, vá de Cheese burger com bacon extra. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'],
                    ['<h4 style="color:#000">HOUSE OF ALL</h4>' +
                    '<img src="images/bd05.jpg" class="img-responsive"><br><strong>R. Dr. Virgílio de Carvalho Pinto, 47 - Pinheiros</strong><br>O House of All é mais do que uma casa. É onde criam-se experiências únicas para engajar a comunidade em volta de novas marcas e costumes locais, não é difícil ver a rua do House of All fechada com muita diversão e coletividade. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'],
                    
                ];
                    
                // Display multiple markers on a map
                var infoWindow = new google.maps.InfoWindow({ maxWidth: 450 }), marker, i;
                
                // Loop through our array of markers & place each one on the map  
                for( i = 0; i < markers.length; i++ ) {
                    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);                    
                    bounds.extend(position);
                    marker = new google.maps.Marker({
                        position: position,
                        map: map,
                        title: markers[i][0],
                        icon: 'http://www.redrose.com.br/goose/images/marker.png'
                    });
                    
                    // Allow each marker to have an info window    
                    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            infoWindow.setContent(infoWindowContent[i][0]);
                            infoWindow.open(map, marker);
                        }
                    })(marker, i));

                    // Automatically center the map fitting all markers on the screen
                    map.fitBounds(bounds);                    
                }

                // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
                var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                    this.setZoom(14);
                    google.maps.event.removeListener(boundsListener);
                });

                
               
            }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>

                   
<div id="map_canvas" class="mapping" style='width:100%;height:450px'></div>
&#13;
&#13;
&#13;

如果我更改此代码的任何部分,地图将停止工作。 我需要它少初始缩放。 我尝试了其他一些操作,例如手动设置缩放(map.setzoom(10);

1 个答案:

答案 0 :(得分:0)

  1. 移除对map.fitBounds的调用:
  2. // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
    
    1. 改为调用map.setCenter(或者只是在初始化map变量时设置所需的中心,同时需要中心和缩放;调用fitbounds设置两者:
    2. map.setCenter(bounds.getCenter());
      

      proof of concept fiddle

      screenshot of resulting map

      代码段

      &#13;
      &#13;
      jQuery(function($) {
        // Asynchronously Load the map API 
        var script = document.createElement('script');
        script.src = "//maps.googleapis.com/maps/api/js?callback=initialize";
        document.body.appendChild(script);
      });
      
      function initialize() {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
          mapTypeId: 'roadmap',
          zoom: 14,
          styles: mapstyles
        };
      
        // Display a map on the page
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      
      
        // Multiple Markers
        var markers = [
          ['UNDERDOG', -23.5606035, -46.6798997],
          ['BRAZ ELETTRICA', -23.5644743, -46.6825759],
          ['CHOPERIA SÃO PAULO', -23.5650709, -46.6833805],
          ['MEATS', -23.564903, -46.6832477],
          ['HOUSE OF ALL', -23.5651321, -46.6847573],
        ];
      
        // Info Window Content
        var infoWindowContent = [
          ['<h4 style="color:#000">UNDERDOG</h4>' +
            '<img src="images/bd01.jpg" class="img-responsive"><br><strong>R. João Moura, 541 – Pinheiros</strong><br>O Underdog é um pequeno bar que serve carnes preparadas na parrilla, o estilo tradicional do churrasco argentino e uruguaio. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'
          ],
          ['<h4 style="color:#000">BRAZ ELETTRICA</h4>' +
            '<img src="images/bd02.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 220 - Pinheiros</strong><br>A Braz Elettrica é a irmã hiperativa da Braz. Inaugurada a menos de um ano em Pinheiros  é sucesso absoluto entre os amantes de uma bela redonda acompanhada de uma boa cerveja. E  agora você já pode combinar as opções da Goose Island, incluindo a cerveja especial de aniversário, a 30th com a sua pizza predileta.'
          ],
          ['<h4 style="color:#000">CHOPERIA SÃO PAULO</h4>' +
            '<img src="images/bd03.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 315 – Pinheiros</strong><br>Na Choperia São Paulo a cada semana são engatados 20 tipos diferentes às torneiras de chopes inclusive as várias opções de Goose Island, sendo uma delas a cerveja especial de aniversário, a 30th.'
          ],
          ['<h4 style="color:#000">MEATS</h4>' +
            '<img src="images/bd04.jpg" class="img-responsive"><br><strong>R. dos Pinheiros, 320 - Pinheiros</strong><br>Sob o comando de Paulo Yoller, o Meats oferece um menu inventivo com grande respeito aos clássicos, na duvida do que pedir, vá de Cheese burger com bacon extra. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'
          ],
          ['<h4 style="color:#000">HOUSE OF ALL</h4>' +
            '<img src="images/bd05.jpg" class="img-responsive"><br><strong>R. Dr. Virgílio de Carvalho Pinto, 47 - Pinheiros</strong><br>O House of All é mais do que uma casa. É onde criam-se experiências únicas para engajar a comunidade em volta de novas marcas e costumes locais, não é difícil ver a rua do House of All fechada com muita diversão e coletividade. Além disso, tem várias opções de Goose Island, incluindo a cerveja especial de aniversário, a 30th.'
          ],
      
        ];
      
        // Display multiple markers on a map
        var infoWindow = new google.maps.InfoWindow({
            maxWidth: 450
          }),
          marker, i;
      
        // Loop through our array of markers & place each one on the map  
        for (i = 0; i < markers.length; i++) {
          var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
          bounds.extend(position);
          marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0],
            icon: 'https://www.redrose.com.br/goose/images/marker.png'
          });
      
          // Allow each marker to have an info window    
          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infoWindow.setContent(infoWindowContent[i][0]);
              infoWindow.open(map, marker);
            }
          })(marker, i));
      
          // Automatically center the map fitting all markers on the screen
          // map.fitBounds(bounds);
          map.setCenter(bounds.getCenter());
        }
        google.maps.event.addListener(map, 'zoom_changed', function() {
          document.getElementById('zoom').innerHTML = "zoom=" + map.getZoom();
        })
        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
          this.setZoom(10);
          google.maps.event.removeListener(boundsListener);
        });
      }
      var mapstyles = [{
          "featureType": "all",
          "elementType": "geometry",
          "stylers": [{
            "color": "#cecfc4"
          }]
        },
        {
          "featureType": "all",
          "elementType": "labels.text.fill",
          "stylers": [{
              "gamma": 0.01
            },
            {
              "lightness": 20
            }
          ]
        },
        {
          "featureType": "all",
          "elementType": "labels.text.stroke",
          "stylers": [{
              "saturation": -31
            },
            {
              "lightness": -33
            },
            {
              "weight": 2
            },
            {
              "gamma": 0.8
            }
          ]
        },
        {
          "featureType": "all",
          "elementType": "labels.icon",
          "stylers": [{
            "visibility": "off"
          }]
        },
        {
          "featureType": "administrative.locality",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "visibility": "off"
          }]
        },
        {
          "featureType": "administrative.neighborhood",
          "elementType": "geometry.stroke",
          "stylers": [{
              "visibility": "off"
            },
            {
              "color": "#ff0000"
            }
          ]
        },
        {
          "featureType": "administrative.neighborhood",
          "elementType": "labels.text.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#666766"
            }
          ]
        },
        {
          "featureType": "administrative.neighborhood",
          "elementType": "labels.text.stroke",
          "stylers": [{
              "visibility": "off"
            },
            {
              "color": "#ff0000"
            }
          ]
        },
        {
          "featureType": "landscape",
          "elementType": "geometry",
          "stylers": [{
              "lightness": 30
            },
            {
              "saturation": 30
            },
            {
              "visibility": "on"
            }
          ]
        },
        {
          "featureType": "landscape.man_made",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#f7f5ee"
            }
          ]
        },
        {
          "featureType": "landscape.natural.landcover",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#f7f5ee"
            }
          ]
        },
        {
          "featureType": "landscape.natural.terrain",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#f7f5ee"
            }
          ]
        },
        {
          "featureType": "poi",
          "elementType": "geometry",
          "stylers": [{
            "saturation": 20
          }]
        },
        {
          "featureType": "poi.park",
          "elementType": "geometry",
          "stylers": [{
              "lightness": 20
            },
            {
              "saturation": -20
            }
          ]
        },
        {
          "featureType": "poi.park",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#d1cabc"
          }]
        },
        {
          "featureType": "road",
          "elementType": "geometry",
          "stylers": [{
              "lightness": 10
            },
            {
              "saturation": -30
            }
          ]
        },
        {
          "featureType": "road",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#cec3bc"
            }
          ]
        },
        {
          "featureType": "road",
          "elementType": "geometry.stroke",
          "stylers": [{
              "saturation": 25
            },
            {
              "lightness": 25
            }
          ]
        },
        {
          "featureType": "road.highway",
          "elementType": "geometry.fill",
          "stylers": [{
              "color": "#d1cabc"
            },
            {
              "visibility": "on"
            }
          ]
        },
        {
          "featureType": "road.highway",
          "elementType": "geometry.stroke",
          "stylers": [{
              "visibility": "off"
            },
            {
              "color": "#ff0000"
            }
          ]
        },
        {
          "featureType": "road.highway",
          "elementType": "labels.text.stroke",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#ff0000"
            }
          ]
        },
        {
          "featureType": "road.highway.controlled_access",
          "elementType": "labels.text.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#666766"
            }
          ]
        },
        {
          "featureType": "road.highway.controlled_access",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "visibility": "off"
          }]
        },
        {
          "featureType": "road.arterial",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#666766"
          }]
        },
        {
          "featureType": "road.arterial",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "visibility": "off"
          }]
        },
        {
          "featureType": "road.local",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#d1cabc"
            }
          ]
        },
        {
          "featureType": "road.local",
          "elementType": "geometry.stroke",
          "stylers": [{
              "visibility": "off"
            },
            {
              "color": "#ff0000"
            }
          ]
        },
        {
          "featureType": "road.local",
          "elementType": "labels.text.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#666766"
            }
          ]
        },
        {
          "featureType": "road.local",
          "elementType": "labels.text.stroke",
          "stylers": [{
              "visibility": "off"
            },
            {
              "color": "#999897"
            }
          ]
        },
        {
          "featureType": "water",
          "elementType": "all",
          "stylers": [{
            "lightness": -20
          }]
        },
        {
          "featureType": "water",
          "elementType": "geometry.fill",
          "stylers": [{
              "visibility": "on"
            },
            {
              "color": "#d1cabc"
            }
          ]
        }
      ]
      &#13;
      html,
      body,
      #map_canvas {
        height: 95%;
        width: 100%;
        margin: 0;
        padding: 0;
      }
      &#13;
      <div id="zoom"></div>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="map_canvas" class="mapping"></div>
      &#13;
      &#13;
      &#13;