设置Google地图视口以自动调整窗格以显示各个位置的(n)标记的位置

dcl*_*901 9 javascript google-maps google-maps-api-3 google-maps-markers

我到目前为止采取的方法是:

function addMarker( query ) {
    var geocoder = new google.maps.Geocoder();
    var afterGeocode = $.Deferred();

    // Geocode 'query' which is the address of a location.
    geocoder.geocode( 
            { address: query }, 
            function( results, status ){

                    if( status === 'OK' ){
                        afterGeocode.resolve( results ); // Activate deferred.
                    }
            }
    );

    afterGeocode.then( function( results ){
        var mOptions = {
            position: results[0].geometry.location,
            map: map
        }

        // Create and drop in marker.
        var marker = new google.maps.Marker( mOptions );
        marker.setAnimation( google.maps.Animation.DROP );      

        var current_bounds = map.getBounds(); // Get current bounds of map
        // use the extend() function of the latlngbounds object
        // to incorporate the location of the marker
        var new_bounds = current_bounds.extend( results[0].geometry.location );
        map.fitBounds( new_bounds ); // fit the map to those bounds
    }); 
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,无论新标记是否适合当前视口,地图都会莫名其妙地缩小一些量.

我究竟做错了什么?

附录

我添加了日志和一个额外的变量来捕获转换的地图边界(new_new_bounds)

current_bounds = // Map bounds before anything is done.
    {-112.39575760000002, 33.60691883366427},
    {-112.39295444655761, 33.639099}

new_bounds = // From after the extend
    {-112.39295444655761, 33.60691883366427}, 
    {-112.39575760000002, 33.639099}

new_new_bounds = // From after the fitbounds
    {-112.33942438265382, 33.588697452015374},
    {-112.44928766390382, 33.657309727063996}
Run Code Online (Sandbox Code Playgroud)

dcl*_*901 9

好吧,所以经过多次争论后,事实证明问题是地图的界限与之后的地图界限不同fitBounds().发生了什么(我推测),谷歌采取你在fitBounds()方法中给它的界限,然后填补它们.每次发送当前边界时fitBounds(),你都不会拟合边界(x,y),你将适合边界(x + m,y + m),其中m =任意边界.

也就是说,最好的方法是:

var current_bounds = map.getBounds();
var marker_pos = marker.getPosition();

if( !current_bounds.contains( marker_pos ) ){

    var new_bounds = current_bounds.extend( marker_pos );
    map.fitBounds( new_bounds );
}
Run Code Online (Sandbox Code Playgroud)

因此,如果放置的标记落在当前地图边界之外,则地图将仅适合边界.希望这可以帮助其他任何人解决这个问题.