【问题标题】:Setting a Google Maps viewport to automatically fit pane for locations of (n) markers of various locations将 Google Maps 视口设置为自动适合各个位置的 (n) 个标记的位置窗格
【发布时间】:2011-08-25 06:05:36
【问题描述】:

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

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}

【问题讨论】:

  • new_bounds 说它的边界在扩展之后是什么?
  • 看起来从 (x1,y1),(x2,y2) -> (x2,y1),(x1,y2) 的边界变化引起了问题。我不是 100%,但这就是我要开始的地方。
  • 首先,通过将 current_bounds 传递给 fitBounds 并查看视图是否移动,确保这不是错误。

标签: javascript google-maps google-maps-api-3 google-maps-markers


【解决方案1】:

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

【讨论】:

  • 我很难听懂您的回答。我只是使用 v3 API 提供的标准库。查询只是一个地址或地址的一部分。
  • 笨蛋,我已经确定了答案!
【解决方案2】:

好的,经过一番争论,问题在于地图的边界与fitBounds() 之后的地图边界不同。会发生什么(我猜想),是 Google 采用您在 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 );
}

因此,仅当放置的标记超出当前地图边界时,地图才适合边界。希望这对遇到此问题的其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多