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

时间:2011-05-13 20:50:45

标签: 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
    }); 
}

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

我做错了什么?

附录

我添加了日志和一个额外的变量来捕获转换后的地图边界(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}

2 个答案:

答案 0 :(得分: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 );
}

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

答案 1 :(得分:0)

可能的解释是您将新标记随机放入z曲线的间隙中。 z曲线recursivley将地图细分为4个较小的图块,但这也是图块之间存在间隙的原因。更好的方法是使用希尔伯特曲线或摩尔曲线进行地图应用。有一个专利搜索算法覆盖这个问题,我认为它被称为四维的多维范围查询。你想寻找Nick的希尔伯特curce四叉树空间索引博客。