如何影响“宽限期"map.fitBounds() [英] How to affect the "grace margin" of map.fitBounds()

查看:18
本文介绍了如何影响“宽限期"map.fitBounds()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在谷歌地图 API v2 中,我们国家的地图非常适合 700x400 像素的地图,如下所示:

In Google maps API v2, map of our country was nicely fitted to 700x400px map with the following:

map.getBoundsZoomLevel(<bounds of our country>)

但是在 API v3 中,map.fitBounds() 方法不适合它在那个缩放级别到 700x400 - 它缩小一个级别.

But in API v3, the map.fitBounds() method doesn't fit it at that zoom level to 700x400 - it zooms out one level.

这意味着 map.fitBounds() 与一些宽限期"或其他东西有关.

This means that map.fitBounds() counts with some "grace margin" or something.

我如何影响这个边距的大小?

推荐答案

这是一个可以在没有自定义边距的情况下尽可能放大地图的解决方案.如果您愿意,您应该能够对其进行调整以考虑一些保证金.

Here's a solution that will zoom into the map as far as possible without a custom margin. You should be able to adapt it to account for some margin if you want to.

我的解决方案基于 此评论一个 Google 网上论坛帖子.不幸的是,对 helper.getProjection() 的调用总是返回 undefined,所以我稍微调整了上面的答案并想出了这个工作代码.

My solution is based on this comment in a Google Groups thread. Unfortunately, the call to helper.getProjection() always returned undefined, so I adapted the above answer a bit and came up with this working code.

只需将您对 map.fitBounds(bounds) 的现有调用替换为 myFitBounds(map, bounds):

Just replace your existing calls to map.fitBounds(bounds) with myFitBounds(map, bounds):

function myFitBounds(myMap, bounds) {
    myMap.fitBounds(bounds);

    var overlayHelper = new google.maps.OverlayView();
    overlayHelper.draw = function () {
        if (!this.ready) {
            var projection = this.getProjection(),
                zoom = getExtraZoom(projection, bounds, myMap.getBounds());
            if (zoom > 0) {
                myMap.setZoom(myMap.getZoom() + zoom);
            }
            this.ready = true;
            google.maps.event.trigger(this, 'ready');
        }
    };
    overlayHelper.setMap(myMap);
}

// LatLngBounds b1, b2 -> zoom increment
function getExtraZoom(projection, expectedBounds, actualBounds) {
    var expectedSize = getSizeInPixels(projection, expectedBounds),
        actualSize = getSizeInPixels(projection, actualBounds);

    if (Math.floor(expectedSize.x) == 0 || Math.floor(expectedSize.y) == 0) {
        return 0;
    }

    var qx = actualSize.x / expectedSize.x;
    var qy = actualSize.y / expectedSize.y;
    var min = Math.min(qx, qy);

    if (min < 1) {
        return 0;
    }

    return Math.floor(Math.log(min) / Math.log(2) /* = log2(min) */);
}

// LatLngBounds bnds -> height and width as a Point
function getSizeInPixels(projection, bounds) {
    var sw = projection.fromLatLngToContainerPixel(bounds.getSouthWest());
    var ne = projection.fromLatLngToContainerPixel(bounds.getNorthEast());
    return new google.maps.Point(Math.abs(sw.y - ne.y), Math.abs(sw.x - ne.x));
}

这篇关于如何影响“宽限期"map.fitBounds()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆