Google Maps zoom gets overridden, when using a kml

2019-01-14 07:38发布

问题:

How do I specify zoom level for google maps in a kml file or why is it that my zoom level gets over ridden when I load this file. My question is actually how do I control zoom of a map for the following link:

http://code.google.com/apis/maps/documentation/javascript/examples/layer-kml-features.html

回答1:

By default, the map is centered and zoomed to the bounding box of the contents of the kml layer.

You can change the default behaviour with preserveViewport property of google.maps.KmlLayerOptions object. If you set it to true the map isn't centered and zoomed.

In the example, use:

var nyLayer = new google.maps.KmlLayer(
                  'http://www.searcharoo.net/SearchKml/newyork.kml',
                  {
                      suppressInfoWindows: true,
                      map: map,
                      preserveViewport: true
                  });

If you want to center and zoom to the contents of the kml layer later, use:

var bounds = nyLayer.getDefaultViewport();
map.fitBounds(bounds);

EDIT:

If you want the map to be always centered (but not zoomed) when the kml layer is loaded, utilize defaultviewport_changed event of the google.maps.KmlLayer object. You have to set the map center to the center of the kml layer default viewport. The event is triggered when the contents of the kml layer are loaded and its default viewport is computed.

google.maps.event.addListener(nyLayer, 'defaultviewport_changed', function() {
   var bounds = nyLayer.getDefaultViewport();
   map.setCenter(bounds.getCenter());
});